Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/calculus/quadrature.py
import math from ..libmp.backend import xrange class QuadratureRule(object): """ Quadrature rules are implemented using this class, in order to simplify the code and provide a common infrastructure for tasks such as error estimation and node caching. You can implement a custom quadrature rule by subclassing :class:`QuadratureRule` and implementing the appropriate methods. The subclass can then be used by :func:`~mpmath.quad` by passing it as the *method* argument. :class:`QuadratureRule` instances are supposed to be singletons. :class:`QuadratureRule` therefore implements instance caching in :func:`~mpmath.__new__`. """ def __init__(self, ctx): self.ctx = ctx self.standard_cache = {} self.transformed_cache = {} self.interval_count = {} def clear(self): """ Delete cached node data. """ self.standard_cache = {} self.transformed_cache = {} self.interval_count = {} def calc_nodes(self, degree, prec, verbose=False): r""" Compute nodes for the standard interval `[-1, 1]`. Subclasses should probably implement only this method, and use :func:`~mpmath.get_nodes` method to retrieve the nodes. """ raise NotImplementedError def get_nodes(self, a, b, degree, prec, verbose=False): """ Return nodes for given interval, degree and precision. The nodes are retrieved from a cache if already computed; otherwise they are computed by calling :func:`~mpmath.calc_nodes` and are then cached. Subclasses should probably not implement this method, but just implement :func:`~mpmath.calc_nodes` for the actual node computation. """ key = (a, b, degree, prec) if key in self.transformed_cache: return self.transformed_cache[key] orig = self.ctx.prec try: self.ctx.prec = prec+20 # Get nodes on standard interval if (degree, prec) in self.standard_cache: nodes = self.standard_cache[degree, prec] else: nodes = self.calc_nodes(degree, prec, verbose) self.standard_cache[degree, prec] = nodes # Transform to general interval nodes = self.transform_nodes(nodes, a, b, verbose) if key in self.interval_count: self.transformed_cache[key] = nodes else: self.interval_count[key] = True finally: self.ctx.prec = orig return nodes def transform_nodes(self, nodes, a, b, verbose=False): r""" Rescale standardized nodes (for `[-1, 1]`) to a general interval `[a, b]`. For a finite interval, a simple linear change of variables is used. Otherwise, the following transformations are used: .. math :: \lbrack a, \infty \rbrack : t = \frac{1}{x} + (a-1) \lbrack -\infty, b \rbrack : t = (b+1) - \frac{1}{x} \lbrack -\infty, \infty \rbrack : t = \frac{x}{\sqrt{1-x^2}} """ ctx = self.ctx a = ctx.convert(a) b = ctx.convert(b) one = ctx.one if (a, b) == (-one, one): return nodes half = ctx.mpf(0.5) new_nodes = [] if ctx.isinf(a) or ctx.isinf(b): if (a, b) == (ctx.ninf, ctx.inf): p05 = -half for x, w in nodes: x2 = x*x px1 = one-x2 spx1 = px1**p05 x = x*spx1 w *= spx1/px1 new_nodes.append((x, w)) elif a == ctx.ninf: b1 = b+1 for x, w in nodes: u = 2/(x+one) x = b1-u w *= half*u**2 new_nodes.append((x, w)) elif b == ctx.inf: a1 = a-1 for x, w in nodes: u = 2/(x+one) x = a1+u w *= half*u**2 new_nodes.append((x, w)) elif a == ctx.inf or b == ctx.ninf: return [(x,-w) for (x,w) in self.transform_nodes(nodes, b, a, verbose)] else: raise NotImplementedError else: # Simple linear change of variables C = (b-a)/2 D = (b+a)/2 for x, w in nodes: new_nodes.append((D+C*x, C*w)) return new_nodes def guess_degree(self, prec): """ Given a desired precision `p` in bits, estimate the degree `m` of the quadrature required to accomplish full accuracy for typical integrals. By default, :func:`~mpmath.quad` will perform up to `m` iterations. The value of `m` should be a slight overestimate, so that "slightly bad" integrals can be dealt with automatically using a few extra iterations. On the other hand, it should not be too big, so :func:`~mpmath.quad` can quit within a reasonable amount of time when it is given an "unsolvable" integral. The default formula used by :func:`~mpmath.guess_degree` is tuned for both :class:`TanhSinh` and :class:`GaussLegendre`. The output is roughly as follows: +---------+---------+ | `p` | `m` | +=========+=========+ | 50 | 6 | +---------+---------+ | 100 | 7 | +---------+---------+ | 500 | 10 | +---------+---------+ | 3000 | 12 | +---------+---------+ This formula is based purely on a limited amount of experimentation and will sometimes be wrong. """ # Expected degree # XXX: use mag g = int(4 + max(0, self.ctx.log(prec/30.0, 2))) # Reasonable "worst case" g += 2 return g def estimate_error(self, results, prec, epsilon): r""" Given results from integrations `[I_1, I_2, \ldots, I_k]` done with a quadrature of rule of degree `1, 2, \ldots, k`, estimate the error of `I_k`. For `k = 2`, we estimate `|I_{\infty}-I_2|` as `|I_2-I_1|`. For `k > 2`, we extrapolate `|I_{\infty}-I_k| \approx |I_{k+1}-I_k|` from `|I_k-I_{k-1}|` and `|I_k-I_{k-2}|` under the assumption that each degree increment roughly doubles the accuracy of the quadrature rule (this is true for both :class:`TanhSinh` and :class:`GaussLegendre`). The extrapolation formula is given by Borwein, Bailey & Girgensohn. Although not very conservative, this method seems to be very robust in practice. """ if len(results) == 2: return abs(results[0]-results[1]) try: if results[-1] == results[-2] == results[-3]: return self.ctx.zero D1 = self.ctx.log(abs(results[-1]-results[-2]), 10) D2 = self.ctx.log(abs(results[-1]-results[-3]), 10) except ValueError: return epsilon D3 = -prec D4 = min(0, max(D1**2/D2, 2*D1, D3)) return self.ctx.mpf(10) ** int(D4) def summation(self, f, points, prec, epsilon, max_degree, verbose=False): """ Main integration function. Computes the 1D integral over the interval specified by *points*. For each subinterval, performs quadrature of degree from 1 up to *max_degree* until :func:`~mpmath.estimate_error` signals convergence. :func:`~mpmath.summation` transforms each subintegration to the standard interval and then calls :func:`~mpmath.sum_next`. """ ctx = self.ctx I = err = ctx.zero for i in xrange(len(points)-1): a, b = points[i], points[i+1] if a == b: continue # XXX: we could use a single variable transformation, # but this is not good in practice. We get better accuracy # by having 0 as an endpoint. if (a, b) == (ctx.ninf, ctx.inf): _f = f f = lambda x: _f(-x) + _f(x) a, b = (ctx.zero, ctx.inf) results = [] for degree in xrange(1, max_degree+1): nodes = self.get_nodes(a, b, degree, prec, verbose) if verbose: print("Integrating from %s to %s (degree %s of %s)" % \ (ctx.nstr(a), ctx.nstr(b), degree, max_degree)) results.append(self.sum_next(f, nodes, degree, prec, results, verbose)) if degree > 1: err = self.estimate_error(results, prec, epsilon) if err <= epsilon: break if verbose: print("Estimated error:", ctx.nstr(err)) I += results[-1] if err > epsilon: if verbose: print("Failed to reach full accuracy. Estimated error:", ctx.nstr(err)) return I, err def sum_next(self, f, nodes, degree, prec, previous, verbose=False): r""" Evaluates the step sum `\sum w_k f(x_k)` where the *nodes* list contains the `(w_k, x_k)` pairs. :func:`~mpmath.summation` will supply the list *results* of values computed by :func:`~mpmath.sum_next` at previous degrees, in case the quadrature rule is able to reuse them. """ return self.ctx.fdot((w, f(x)) for (x,w) in nodes) class TanhSinh(QuadratureRule): r""" This class implements "tanh-sinh" or "doubly exponential" quadrature. This quadrature rule is based on the Euler-Maclaurin integral formula. By performing a change of variables involving nested exponentials / hyperbolic functions (hence the name), the derivatives at the endpoints vanish rapidly. Since the error term in the Euler-Maclaurin formula depends on the derivatives at the endpoints, a simple step sum becomes extremely accurate. In practice, this means that doubling the number of evaluation points roughly doubles the number of accurate digits. Comparison to Gauss-Legendre: * Initial computation of nodes is usually faster * Handles endpoint singularities better * Handles infinite integration intervals better * Is slower for smooth integrands once nodes have been computed The implementation of the tanh-sinh algorithm is based on the description given in Borwein, Bailey & Girgensohn, "Experimentation in Mathematics - Computational Paths to Discovery", A K Peters, 2003, pages 312-313. In the present implementation, a few improvements have been made: * A more efficient scheme is used to compute nodes (exploiting recurrence for the exponential function) * The nodes are computed successively instead of all at once Various documents describing the algorithm are available online, e.g.: * http://crd.lbl.gov/~dhbailey/dhbpapers/dhb-tanh-sinh.pdf * http://users.cs.dal.ca/~jborwein/tanh-sinh.pdf """ def sum_next(self, f, nodes, degree, prec, previous, verbose=False): """ Step sum for tanh-sinh quadrature of degree `m`. We exploit the fact that half of the abscissas at degree `m` are precisely the abscissas from degree `m-1`. Thus reusing the result from the previous level allows a 2x speedup. """ h = self.ctx.mpf(2)**(-degree) # Abscissas overlap, so reusing saves half of the time if previous: S = previous[-1]/(h*2) else: S = self.ctx.zero S += self.ctx.fdot((w,f(x)) for (x,w) in nodes) return h*S def calc_nodes(self, degree, prec, verbose=False): r""" The abscissas and weights for tanh-sinh quadrature of degree `m` are given by .. math:: x_k = \tanh(\pi/2 \sinh(t_k)) w_k = \pi/2 \cosh(t_k) / \cosh(\pi/2 \sinh(t_k))^2 where `t_k = t_0 + hk` for a step length `h \sim 2^{-m}`. The list of nodes is actually infinite, but the weights die off so rapidly that only a few are needed. """ ctx = self.ctx nodes = [] extra = 20 ctx.prec += extra tol = ctx.ldexp(1, -prec-10) pi4 = ctx.pi/4 # For simplicity, we work in steps h = 1/2^n, with the first point # offset so that we can reuse the sum from the previous degree # We define degree 1 to include the "degree 0" steps, including # the point x = 0. (It doesn't work well otherwise; not sure why.) t0 = ctx.ldexp(1, -degree) if degree == 1: #nodes.append((mpf(0), pi4)) #nodes.append((-mpf(0), pi4)) nodes.append((ctx.zero, ctx.pi/2)) h = t0 else: h = t0*2 # Since h is fixed, we can compute the next exponential # by simply multiplying by exp(h) expt0 = ctx.exp(t0) a = pi4 * expt0 b = pi4 / expt0 udelta = ctx.exp(h) urdelta = 1/udelta for k in xrange(0, 20*2**degree+1): # Reference implementation: # t = t0 + k*h # x = tanh(pi/2 * sinh(t)) # w = pi/2 * cosh(t) / cosh(pi/2 * sinh(t))**2 # Fast implementation. Note that c = exp(pi/2 * sinh(t)) c = ctx.exp(a-b) d = 1/c co = (c+d)/2 si = (c-d)/2 x = si / co w = (a+b) / co**2 diff = abs(x-1) if diff <= tol: break nodes.append((x, w)) nodes.append((-x, w)) a *= udelta b *= urdelta if verbose and k % 300 == 150: # Note: the number displayed is rather arbitrary. Should # figure out how to print something that looks more like a # percentage print("Calculating nodes:", ctx.nstr(-ctx.log(diff, 10) / prec)) ctx.prec -= extra return nodes class GaussLegendre(QuadratureRule): """ This class implements Gauss-Legendre quadrature, which is exceptionally efficient for polynomials and polynomial-like (i.e. very smooth) integrands. The abscissas and weights are given by roots and values of Legendre polynomials, which are the orthogonal polynomials on `[-1, 1]` with respect to the unit weight (see :func:`~mpmath.legendre`). In this implementation, we take the "degree" `m` of the quadrature to denote a Gauss-Legendre rule of degree `3 \cdot 2^m` (following Borwein, Bailey & Girgensohn). This way we get quadratic, rather than linear, convergence as the degree is incremented. Comparison to tanh-sinh quadrature: * Is faster for smooth integrands once nodes have been computed * Initial computation of nodes is usually slower * Handles endpoint singularities worse * Handles infinite integration intervals worse """ def calc_nodes(self, degree, prec, verbose=False): """ Calculates the abscissas and weights for Gauss-Legendre quadrature of degree of given degree (actually `3 \cdot 2^m`). """ ctx = self.ctx # It is important that the epsilon is set lower than the # "real" epsilon epsilon = ctx.ldexp(1, -prec-8) # Fairly high precision might be required for accurate # evaluation of the roots orig = ctx.prec ctx.prec = int(prec*1.5) if degree == 1: x = ctx.sqrt(ctx.mpf(3)/5) w = ctx.mpf(5)/9 nodes = [(-x,w),(ctx.zero,ctx.mpf(8)/9),(x,w)] ctx.prec = orig return nodes nodes = [] n = 3*2**(degree-1) upto = n//2 + 1 for j in xrange(1, upto): # Asymptotic formula for the roots r = ctx.mpf(math.cos(math.pi*(j-0.25)/(n+0.5))) # Newton iteration while 1: t1, t2 = 1, 0 # Evaluates the Legendre polynomial using its defining # recurrence relation for j1 in xrange(1,n+1): t3, t2, t1 = t2, t1, ((2*j1-1)*r*t1 - (j1-1)*t2)/j1 t4 = n*(r*t1- t2)/(r**2-1) t5 = r a = t1/t4 r = r - a if abs(a) < epsilon: break x = r w = 2/((1-r**2)*t4**2) if verbose and j % 30 == 15: print("Computing nodes (%i of %i)" % (j, upto)) nodes.append((x, w)) nodes.append((-x, w)) ctx.prec = orig return nodes class QuadratureMethods(object): def __init__(ctx, *args, **kwargs): ctx._gauss_legendre = GaussLegendre(ctx) ctx._tanh_sinh = TanhSinh(ctx) def quad(ctx, f, *points, **kwargs): r""" Computes a single, double or triple integral over a given 1D interval, 2D rectangle, or 3D cuboid. A basic example:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> quad(sin, [0, pi]) 2.0 A basic 2D integral:: >>> f = lambda x, y: cos(x+y/2) >>> quad(f, [-pi/2, pi/2], [0, pi]) 4.0 **Interval format** The integration range for each dimension may be specified using a list or tuple. Arguments are interpreted as follows: ``quad(f, [x1, x2])`` -- calculates `\int_{x_1}^{x_2} f(x) \, dx` ``quad(f, [x1, x2], [y1, y2])`` -- calculates `\int_{x_1}^{x_2} \int_{y_1}^{y_2} f(x,y) \, dy \, dx` ``quad(f, [x1, x2], [y1, y2], [z1, z2])`` -- calculates `\int_{x_1}^{x_2} \int_{y_1}^{y_2} \int_{z_1}^{z_2} f(x,y,z) \, dz \, dy \, dx` Endpoints may be finite or infinite. An interval descriptor may also contain more than two points. In this case, the integration is split into subintervals, between each pair of consecutive points. This is useful for dealing with mid-interval discontinuities, or integrating over large intervals where the function is irregular or oscillates. **Options** :func:`~mpmath.quad` recognizes the following keyword arguments: *method* Chooses integration algorithm (described below). *error* If set to true, :func:`~mpmath.quad` returns `(v, e)` where `v` is the integral and `e` is the estimated error. *maxdegree* Maximum degree of the quadrature rule to try before quitting. *verbose* Print details about progress. **Algorithms** Mpmath presently implements two integration algorithms: tanh-sinh quadrature and Gauss-Legendre quadrature. These can be selected using *method='tanh-sinh'* or *method='gauss-legendre'* or by passing the classes *method=TanhSinh*, *method=GaussLegendre*. The functions :func:`~mpmath.quadts` and :func:`~mpmath.quadgl` are also available as shortcuts. Both algorithms have the property that doubling the number of evaluation points roughly doubles the accuracy, so both are ideal for high precision quadrature (hundreds or thousands of digits). At high precision, computing the nodes and weights for the integration can be expensive (more expensive than computing the function values). To make repeated integrations fast, nodes are automatically cached. The advantages of the tanh-sinh algorithm are that it tends to handle endpoint singularities well, and that the nodes are cheap to compute on the first run. For these reasons, it is used by :func:`~mpmath.quad` as the default algorithm. Gauss-Legendre quadrature often requires fewer function evaluations, and is therefore often faster for repeated use, but the algorithm does not handle endpoint singularities as well and the nodes are more expensive to compute. Gauss-Legendre quadrature can be a better choice if the integrand is smooth and repeated integrations are required (e.g. for multiple integrals). See the documentation for :class:`TanhSinh` and :class:`GaussLegendre` for additional details. **Examples of 1D integrals** Intervals may be infinite or half-infinite. The following two examples evaluate the limits of the inverse tangent function (`\int 1/(1+x^2) = \tan^{-1} x`), and the Gaussian integral `\int_{\infty}^{\infty} \exp(-x^2)\,dx = \sqrt{\pi}`:: >>> mp.dps = 15 >>> quad(lambda x: 2/(x**2+1), [0, inf]) 3.14159265358979 >>> quad(lambda x: exp(-x**2), [-inf, inf])**2 3.14159265358979 Integrals can typically be resolved to high precision. The following computes 50 digits of `\pi` by integrating the area of the half-circle defined by `x^2 + y^2 \le 1`, `-1 \le x \le 1`, `y \ge 0`:: >>> mp.dps = 50 >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1]) 3.1415926535897932384626433832795028841971693993751 One can just as well compute 1000 digits (output truncated):: >>> mp.dps = 1000 >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1]) #doctest:+ELLIPSIS 3.141592653589793238462643383279502884...216420198 Complex integrals are supported. The following computes a residue at `z = 0` by integrating counterclockwise along the diamond-shaped path from `1` to `+i` to `-1` to `-i` to `1`:: >>> mp.dps = 15 >>> chop(quad(lambda z: 1/z, [1,j,-1,-j,1])) (0.0 + 6.28318530717959j) **Examples of 2D and 3D integrals** Here are several nice examples of analytically solvable 2D integrals (taken from MathWorld [1]) that can be evaluated to high precision fairly rapidly by :func:`~mpmath.quad`:: >>> mp.dps = 30 >>> f = lambda x, y: (x-1)/((1-x*y)*log(x*y)) >>> quad(f, [0, 1], [0, 1]) 0.577215664901532860606512090082 >>> +euler 0.577215664901532860606512090082 >>> f = lambda x, y: 1/sqrt(1+x**2+y**2) >>> quad(f, [-1, 1], [-1, 1]) 3.17343648530607134219175646705 >>> 4*log(2+sqrt(3))-2*pi/3 3.17343648530607134219175646705 >>> f = lambda x, y: 1/(1-x**2 * y**2) >>> quad(f, [0, 1], [0, 1]) 1.23370055013616982735431137498 >>> pi**2 / 8 1.23370055013616982735431137498 >>> quad(lambda x, y: 1/(1-x*y), [0, 1], [0, 1]) 1.64493406684822643647241516665 >>> pi**2 / 6 1.64493406684822643647241516665 Multiple integrals may be done over infinite ranges:: >>> mp.dps = 15 >>> print(quad(lambda x,y: exp(-x-y), [0, inf], [1, inf])) 0.367879441171442 >>> print(1/e) 0.367879441171442 For nonrectangular areas, one can call :func:`~mpmath.quad` recursively. For example, we can replicate the earlier example of calculating `\pi` by integrating over the unit-circle, and actually use double quadrature to actually measure the area circle:: >>> f = lambda x: quad(lambda y: 1, [-sqrt(1-x**2), sqrt(1-x**2)]) >>> quad(f, [-1, 1]) 3.14159265358979 Here is a simple triple integral:: >>> mp.dps = 15 >>> f = lambda x,y,z: x*y/(1+z) >>> quad(f, [0,1], [0,1], [1,2], method='gauss-legendre') 0.101366277027041 >>> (log(3)-log(2))/4 0.101366277027041 **Singularities** Both tanh-sinh and Gauss-Legendre quadrature are designed to integrate smooth (infinitely differentiable) functions. Neither algorithm copes well with mid-interval singularities (such as mid-interval discontinuities in `f(x)` or `f'(x)`). The best solution is to split the integral into parts:: >>> mp.dps = 15 >>> quad(lambda x: abs(sin(x)), [0, 2*pi]) # Bad 3.99900894176779 >>> quad(lambda x: abs(sin(x)), [0, pi, 2*pi]) # Good 4.0 The tanh-sinh rule often works well for integrands having a singularity at one or both endpoints:: >>> mp.dps = 15 >>> quad(log, [0, 1], method='tanh-sinh') # Good -1.0 >>> quad(log, [0, 1], method='gauss-legendre') # Bad -0.999932197413801 However, the result may still be inaccurate for some functions:: >>> quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh') 1.99999999946942 This problem is not due to the quadrature rule per se, but to numerical amplification of errors in the nodes. The problem can be circumvented by temporarily increasing the precision:: >>> mp.dps = 30 >>> a = quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh') >>> mp.dps = 15 >>> +a 2.0 **Highly variable functions** For functions that are smooth (in the sense of being infinitely differentiable) but contain sharp mid-interval peaks or many "bumps", :func:`~mpmath.quad` may fail to provide full accuracy. For example, with default settings, :func:`~mpmath.quad` is able to integrate `\sin(x)` accurately over an interval of length 100 but not over length 1000:: >>> quad(sin, [0, 100]); 1-cos(100) # Good 0.137681127712316 0.137681127712316 >>> quad(sin, [0, 1000]); 1-cos(1000) # Bad -37.8587612408485 0.437620923709297 One solution is to break the integration into 10 intervals of length 100:: >>> quad(sin, linspace(0, 1000, 10)) # Good 0.437620923709297 Another is to increase the degree of the quadrature:: >>> quad(sin, [0, 1000], maxdegree=10) # Also good 0.437620923709297 Whether splitting the interval or increasing the degree is more efficient differs from case to case. Another example is the function `1/(1+x^2)`, which has a sharp peak centered around `x = 0`:: >>> f = lambda x: 1/(1+x**2) >>> quad(f, [-100, 100]) # Bad 3.64804647105268 >>> quad(f, [-100, 100], maxdegree=10) # Good 3.12159332021646 >>> quad(f, [-100, 0, 100]) # Also good 3.12159332021646 **References** 1. http://mathworld.wolfram.com/DoubleIntegral.html """ rule = kwargs.get('method', 'tanh-sinh') if type(rule) is str: if rule == 'tanh-sinh': rule = ctx._tanh_sinh elif rule == 'gauss-legendre': rule = ctx._gauss_legendre else: raise ValueError("unknown quadrature rule: %s" % rule) else: rule = rule(ctx) verbose = kwargs.get('verbose') dim = len(points) orig = prec = ctx.prec epsilon = ctx.eps/8 m = kwargs.get('maxdegree') or rule.guess_degree(prec) points = [ctx._as_points(p) for p in points] try: ctx.prec += 20 if dim == 1: v, err = rule.summation(f, points[0], prec, epsilon, m, verbose) elif dim == 2: v, err = rule.summation(lambda x: \ rule.summation(lambda y: f(x,y), \ points[1], prec, epsilon, m)[0], points[0], prec, epsilon, m, verbose) elif dim == 3: v, err = rule.summation(lambda x: \ rule.summation(lambda y: \ rule.summation(lambda z: f(x,y,z), \ points[2], prec, epsilon, m)[0], points[1], prec, epsilon, m)[0], points[0], prec, epsilon, m, verbose) else: raise NotImplementedError("quadrature must have dim 1, 2 or 3") finally: ctx.prec = orig if kwargs.get("error"): return +v, err return +v def quadts(ctx, *args, **kwargs): """ Performs tanh-sinh quadrature. The call quadts(func, *points, ...) is simply a shortcut for: quad(func, *points, ..., method=TanhSinh) For example, a single integral and a double integral: quadts(lambda x: exp(cos(x)), [0, 1]) quadts(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1]) See the documentation for quad for information about how points arguments and keyword arguments are parsed. See documentation for TanhSinh for algorithmic information about tanh-sinh quadrature. """ kwargs['method'] = 'tanh-sinh' return ctx.quad(*args, **kwargs) def quadgl(ctx, *args, **kwargs): """ Performs Gauss-Legendre quadrature. The call quadgl(func, *points, ...) is simply a shortcut for: quad(func, *points, ..., method=GaussLegendre) For example, a single integral and a double integral: quadgl(lambda x: exp(cos(x)), [0, 1]) quadgl(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1]) See the documentation for quad for information about how points arguments and keyword arguments are parsed. See documentation for TanhSinh for algorithmic information about tanh-sinh quadrature. """ kwargs['method'] = 'gauss-legendre' return ctx.quad(*args, **kwargs) def quadosc(ctx, f, interval, omega=None, period=None, zeros=None): r""" Calculates .. math :: I = \int_a^b f(x) dx where at least one of `a` and `b` is infinite and where `f(x) = g(x) \cos(\omega x + \phi)` for some slowly decreasing function `g(x)`. With proper input, :func:`~mpmath.quadosc` can also handle oscillatory integrals where the oscillation rate is different from a pure sine or cosine wave. In the standard case when `|a| < \infty, b = \infty`, :func:`~mpmath.quadosc` works by evaluating the infinite series .. math :: I = \int_a^{x_1} f(x) dx + \sum_{k=1}^{\infty} \int_{x_k}^{x_{k+1}} f(x) dx where `x_k` are consecutive zeros (alternatively some other periodic reference point) of `f(x)`. Accordingly, :func:`~mpmath.quadosc` requires information about the zeros of `f(x)`. For a periodic function, you can specify the zeros by either providing the angular frequency `\omega` (*omega*) or the *period* `2 \pi/\omega`. In general, you can specify the `n`-th zero by providing the *zeros* arguments. Below is an example of each:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> f = lambda x: sin(3*x)/(x**2+1) >>> quadosc(f, [0,inf], omega=3) 0.37833007080198 >>> quadosc(f, [0,inf], period=2*pi/3) 0.37833007080198 >>> quadosc(f, [0,inf], zeros=lambda n: pi*n/3) 0.37833007080198 >>> (ei(3)*exp(-3)-exp(3)*ei(-3))/2 # Computed by Mathematica 0.37833007080198 Note that *zeros* was specified to multiply `n` by the *half-period*, not the full period. In theory, it does not matter whether each partial integral is done over a half period or a full period. However, if done over half-periods, the infinite series passed to :func:`~mpmath.nsum` becomes an *alternating series* and this typically makes the extrapolation much more efficient. Here is an example of an integration over the entire real line, and a half-infinite integration starting at `-\infty`:: >>> quadosc(lambda x: cos(x)/(1+x**2), [-inf, inf], omega=1) 1.15572734979092 >>> pi/e 1.15572734979092 >>> quadosc(lambda x: cos(x)/x**2, [-inf, -1], period=2*pi) -0.0844109505595739 >>> cos(1)+si(1)-pi/2 -0.0844109505595738 Of course, the integrand may contain a complex exponential just as well as a real sine or cosine:: >>> quadosc(lambda x: exp(3*j*x)/(1+x**2), [-inf,inf], omega=3) (0.156410688228254 + 0.0j) >>> pi/e**3 0.156410688228254 >>> quadosc(lambda x: exp(3*j*x)/(2+x+x**2), [-inf,inf], omega=3) (0.00317486988463794 - 0.0447701735209082j) >>> 2*pi/sqrt(7)/exp(3*(j+sqrt(7))/2) (0.00317486988463794 - 0.0447701735209082j) **Non-periodic functions** If `f(x) = g(x) h(x)` for some function `h(x)` that is not strictly periodic, *omega* or *period* might not work, and it might be necessary to use *zeros*. A notable exception can be made for Bessel functions which, though not periodic, are "asymptotically periodic" in a sufficiently strong sense that the sum extrapolation will work out:: >>> quadosc(j0, [0, inf], period=2*pi) 1.0 >>> quadosc(j1, [0, inf], period=2*pi) 1.0 More properly, one should provide the exact Bessel function zeros:: >>> j0zero = lambda n: findroot(j0, pi*(n-0.25)) >>> quadosc(j0, [0, inf], zeros=j0zero) 1.0 For an example where *zeros* becomes necessary, consider the complete Fresnel integrals .. math :: \int_0^{\infty} \cos x^2\,dx = \int_0^{\infty} \sin x^2\,dx = \sqrt{\frac{\pi}{8}}. Although the integrands do not decrease in magnitude as `x \to \infty`, the integrals are convergent since the oscillation rate increases (causing consecutive periods to asymptotically cancel out). These integrals are virtually impossible to calculate to any kind of accuracy using standard quadrature rules. However, if one provides the correct asymptotic distribution of zeros (`x_n \sim \sqrt{n}`), :func:`~mpmath.quadosc` works:: >>> mp.dps = 30 >>> f = lambda x: cos(x**2) >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n)) 0.626657068657750125603941321203 >>> f = lambda x: sin(x**2) >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n)) 0.626657068657750125603941321203 >>> sqrt(pi/8) 0.626657068657750125603941321203 (Interestingly, these integrals can still be evaluated if one places some other constant than `\pi` in the square root sign.) In general, if `f(x) \sim g(x) \cos(h(x))`, the zeros follow the inverse-function distribution `h^{-1}(x)`:: >>> mp.dps = 15 >>> f = lambda x: sin(exp(x)) >>> quadosc(f, [1,inf], zeros=lambda n: log(n)) -0.25024394235267 >>> pi/2-si(e) -0.250243942352671 **Non-alternating functions** If the integrand oscillates around a positive value, without alternating signs, the extrapolation might fail. A simple trick that sometimes works is to multiply or divide the frequency by 2:: >>> f = lambda x: 1/x**2+sin(x)/x**4 >>> quadosc(f, [1,inf], omega=1) # Bad 1.28642190869861 >>> quadosc(f, [1,inf], omega=0.5) # Perfect 1.28652953559617 >>> 1+(cos(1)+ci(1)+sin(1))/6 1.28652953559617 **Fast decay** :func:`~mpmath.quadosc` is primarily useful for slowly decaying integrands. If the integrand decreases exponentially or faster, :func:`~mpmath.quad` will likely handle it without trouble (and generally be much faster than :func:`~mpmath.quadosc`):: >>> quadosc(lambda x: cos(x)/exp(x), [0, inf], omega=1) 0.5 >>> quad(lambda x: cos(x)/exp(x), [0, inf]) 0.5 """ a, b = ctx._as_points(interval) a = ctx.convert(a) b = ctx.convert(b) if [omega, period, zeros].count(None) != 2: raise ValueError( \ "must specify exactly one of omega, period, zeros") if a == ctx.ninf and b == ctx.inf: s1 = ctx.quadosc(f, [a, 0], omega=omega, zeros=zeros, period=period) s2 = ctx.quadosc(f, [0, b], omega=omega, zeros=zeros, period=period) return s1 + s2 if a == ctx.ninf: if zeros: return ctx.quadosc(lambda x:f(-x), [-b,-a], lambda n: zeros(-n)) else: return ctx.quadosc(lambda x:f(-x), [-b,-a], omega=omega, period=period) if b != ctx.inf: raise ValueError("quadosc requires an infinite integration interval") if not zeros: if omega: period = 2*ctx.pi/omega zeros = lambda n: n*period/2 #for n in range(1,10): # p = zeros(n) # if p > a: # break #if n >= 9: # raise ValueError("zeros do not appear to be correctly indexed") n = 1 s = ctx.quadgl(f, [a, zeros(n)]) def term(k): return ctx.quadgl(f, [zeros(k), zeros(k+1)]) s += ctx.nsum(term, [n, ctx.inf]) return s if __name__ == '__main__': import doctest doctest.testmod()
38,334
36.955446
90
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/calculus/odes.py
from bisect import bisect from ..libmp.backend import xrange class ODEMethods(object): pass def ode_taylor(ctx, derivs, x0, y0, tol_prec, n): h = tol = ctx.ldexp(1, -tol_prec) dim = len(y0) xs = [x0] ys = [y0] x = x0 y = y0 orig = ctx.prec try: ctx.prec = orig*(1+n) # Use n steps with Euler's method to get # evaluation points for derivatives for i in range(n): fxy = derivs(x, y) y = [y[i]+h*fxy[i] for i in xrange(len(y))] x += h xs.append(x) ys.append(y) # Compute derivatives ser = [[] for d in range(dim)] for j in range(n+1): s = [0]*dim b = (-1) ** (j & 1) k = 1 for i in range(j+1): for d in range(dim): s[d] += b * ys[i][d] b = (b * (j-k+1)) // (-k) k += 1 scale = h**(-j) / ctx.fac(j) for d in range(dim): s[d] = s[d] * scale ser[d].append(s[d]) finally: ctx.prec = orig # Estimate radius for which we can get full accuracy. # XXX: do this right for zeros radius = ctx.one for ts in ser: if ts[-1]: radius = min(radius, ctx.nthroot(tol/abs(ts[-1]), n)) radius /= 2 # XXX return ser, x0+radius def odefun(ctx, F, x0, y0, tol=None, degree=None, method='taylor', verbose=False): r""" Returns a function `y(x) = [y_0(x), y_1(x), \ldots, y_n(x)]` that is a numerical solution of the `n+1`-dimensional first-order ordinary differential equation (ODE) system .. math :: y_0'(x) = F_0(x, [y_0(x), y_1(x), \ldots, y_n(x)]) y_1'(x) = F_1(x, [y_0(x), y_1(x), \ldots, y_n(x)]) \vdots y_n'(x) = F_n(x, [y_0(x), y_1(x), \ldots, y_n(x)]) The derivatives are specified by the vector-valued function *F* that evaluates `[y_0', \ldots, y_n'] = F(x, [y_0, \ldots, y_n])`. The initial point `x_0` is specified by the scalar argument *x0*, and the initial value `y(x_0) = [y_0(x_0), \ldots, y_n(x_0)]` is specified by the vector argument *y0*. For convenience, if the system is one-dimensional, you may optionally provide just a scalar value for *y0*. In this case, *F* should accept a scalar *y* argument and return a scalar. The solution function *y* will return scalar values instead of length-1 vectors. Evaluation of the solution function `y(x)` is permitted for any `x \ge x_0`. A high-order ODE can be solved by transforming it into first-order vector form. This transformation is described in standard texts on ODEs. Examples will also be given below. **Options, speed and accuracy** By default, :func:`~mpmath.odefun` uses a high-order Taylor series method. For reasonably well-behaved problems, the solution will be fully accurate to within the working precision. Note that *F* must be possible to evaluate to very high precision for the generation of Taylor series to work. To get a faster but less accurate solution, you can set a large value for *tol* (which defaults roughly to *eps*). If you just want to plot the solution or perform a basic simulation, *tol = 0.01* is likely sufficient. The *degree* argument controls the degree of the solver (with *method='taylor'*, this is the degree of the Taylor series expansion). A higher degree means that a longer step can be taken before a new local solution must be generated from *F*, meaning that fewer steps are required to get from `x_0` to a given `x_1`. On the other hand, a higher degree also means that each local solution becomes more expensive (i.e., more evaluations of *F* are required per step, and at higher precision). The optimal setting therefore involves a tradeoff. Generally, decreasing the *degree* for Taylor series is likely to give faster solution at low precision, while increasing is likely to be better at higher precision. The function object returned by :func:`~mpmath.odefun` caches the solutions at all step points and uses polynomial interpolation between step points. Therefore, once `y(x_1)` has been evaluated for some `x_1`, `y(x)` can be evaluated very quickly for any `x_0 \le x \le x_1`. and continuing the evaluation up to `x_2 > x_1` is also fast. **Examples of first-order ODEs** We will solve the standard test problem `y'(x) = y(x), y(0) = 1` which has explicit solution `y(x) = \exp(x)`:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> f = odefun(lambda x, y: y, 0, 1) >>> for x in [0, 1, 2.5]: ... print((f(x), exp(x))) ... (1.0, 1.0) (2.71828182845905, 2.71828182845905) (12.1824939607035, 12.1824939607035) The solution with high precision:: >>> mp.dps = 50 >>> f = odefun(lambda x, y: y, 0, 1) >>> f(1) 2.7182818284590452353602874713526624977572470937 >>> exp(1) 2.7182818284590452353602874713526624977572470937 Using the more general vectorized form, the test problem can be input as (note that *f* returns a 1-element vector):: >>> mp.dps = 15 >>> f = odefun(lambda x, y: [y[0]], 0, [1]) >>> f(1) [2.71828182845905] :func:`~mpmath.odefun` can solve nonlinear ODEs, which are generally impossible (and at best difficult) to solve analytically. As an example of a nonlinear ODE, we will solve `y'(x) = x \sin(y(x))` for `y(0) = \pi/2`. An exact solution happens to be known for this problem, and is given by `y(x) = 2 \tan^{-1}\left(\exp\left(x^2/2\right)\right)`:: >>> f = odefun(lambda x, y: x*sin(y), 0, pi/2) >>> for x in [2, 5, 10]: ... print((f(x), 2*atan(exp(mpf(x)**2/2)))) ... (2.87255666284091, 2.87255666284091) (3.14158520028345, 3.14158520028345) (3.14159265358979, 3.14159265358979) If `F` is independent of `y`, an ODE can be solved using direct integration. We can therefore obtain a reference solution with :func:`~mpmath.quad`:: >>> f = lambda x: (1+x**2)/(1+x**3) >>> g = odefun(lambda x, y: f(x), pi, 0) >>> g(2*pi) 0.72128263801696 >>> quad(f, [pi, 2*pi]) 0.72128263801696 **Examples of second-order ODEs** We will solve the harmonic oscillator equation `y''(x) + y(x) = 0`. To do this, we introduce the helper functions `y_0 = y, y_1 = y_0'` whereby the original equation can be written as `y_1' + y_0' = 0`. Put together, we get the first-order, two-dimensional vector ODE .. math :: \begin{cases} y_0' = y_1 \\ y_1' = -y_0 \end{cases} To get a well-defined IVP, we need two initial values. With `y(0) = y_0(0) = 1` and `-y'(0) = y_1(0) = 0`, the problem will of course be solved by `y(x) = y_0(x) = \cos(x)` and `-y'(x) = y_1(x) = \sin(x)`. We check this:: >>> f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0]) >>> for x in [0, 1, 2.5, 10]: ... nprint(f(x), 15) ... nprint([cos(x), sin(x)], 15) ... print("---") ... [1.0, 0.0] [1.0, 0.0] --- [0.54030230586814, 0.841470984807897] [0.54030230586814, 0.841470984807897] --- [-0.801143615546934, 0.598472144103957] [-0.801143615546934, 0.598472144103957] --- [-0.839071529076452, -0.54402111088937] [-0.839071529076452, -0.54402111088937] --- Note that we get both the sine and the cosine solutions simultaneously. **TODO** * Better automatic choice of degree and step size * Make determination of Taylor series convergence radius more robust * Allow solution for `x < x_0` * Allow solution for complex `x` * Test for difficult (ill-conditioned) problems * Implement Runge-Kutta and other algorithms """ if tol: tol_prec = int(-ctx.log(tol, 2))+10 else: tol_prec = ctx.prec+10 degree = degree or (3 + int(3*ctx.dps/2.)) workprec = ctx.prec + 40 try: len(y0) return_vector = True except TypeError: F_ = F F = lambda x, y: [F_(x, y[0])] y0 = [y0] return_vector = False ser, xb = ode_taylor(ctx, F, x0, y0, tol_prec, degree) series_boundaries = [x0, xb] series_data = [(ser, x0, xb)] # We will be working with vectors of Taylor series def mpolyval(ser, a): return [ctx.polyval(s[::-1], a) for s in ser] # Find nearest expansion point; compute if necessary def get_series(x): if x < x0: raise ValueError n = bisect(series_boundaries, x) if n < len(series_boundaries): return series_data[n-1] while 1: ser, xa, xb = series_data[-1] if verbose: print("Computing Taylor series for [%f, %f]" % (xa, xb)) y = mpolyval(ser, xb-xa) xa = xb ser, xb = ode_taylor(ctx, F, xb, y, tol_prec, degree) series_boundaries.append(xb) series_data.append((ser, xa, xb)) if x <= xb: return series_data[-1] # Evaluation function def interpolant(x): x = ctx.convert(x) orig = ctx.prec try: ctx.prec = workprec ser, xa, xb = get_series(x) y = mpolyval(ser, x-xa) finally: ctx.prec = orig if return_vector: return [+yk for yk in y] else: return +y[0] return interpolant ODEMethods.odefun = odefun if __name__ == "__main__": import doctest doctest.testmod()
9,908
33.287197
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/calculus/__init__.py
from . import calculus # XXX: hack to set methods from . import approximation from . import differentiation from . import extrapolation from . import polynomials
162
22.285714
29
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/calculus/inverselaplace.py
# contributed to mpmath by Kristopher L. Kuhlman, February 2017 class InverseLaplaceTransform(object): r""" Inverse Laplace transform methods are implemented using this class, in order to simplify the code and provide a common infrastructure. Implement a custom inverse Laplace transform algorithm by subclassing :class:`InverseLaplaceTransform` and implementing the appropriate methods. The subclass can then be used by :func:`~mpmath.invertlaplace` by passing it as the *method* argument. """ def __init__(self,ctx): self.ctx = ctx def calc_laplace_parameter(self,t,**kwargs): r""" Determine the vector of Laplace parameter values needed for an algorithm, this will depend on the choice of algorithm (de Hoog is default), the algorithm-specific parameters passed (or default ones), and desired time. """ raise NotImplementedError def calc_time_domain_solution(self,fp): r""" Compute the time domain solution, after computing the Laplace-space function evaluations at the abscissa required for the algorithm. Abscissa computed for one algorithm are typically not useful for another algorithm. """ raise NotImplementedError class FixedTalbot(InverseLaplaceTransform): def calc_laplace_parameter(self,t,**kwargs): r"""The "fixed" Talbot method deforms the Bromwich contour towards `-\infty` in the shape of a parabola. Traditionally the Talbot algorithm has adjustable parameters, but the "fixed" version does not. The `r` parameter could be passed in as a parameter, if you want to override the default given by (Abate & Valko, 2004). The Laplace parameter is sampled along a parabola opening along the negative imaginary axis, with the base of the parabola along the real axis at `p=\frac{r}{t_\mathrm{max}}`. As the number of terms used in the approximation (degree) grows, the abscissa required for function evaluation tend towards `-\infty`, requiring high precision to prevent overflow. If any poles, branch cuts or other singularities exist such that the deformed Bromwich contour lies to the left of the singularity, the method will fail. **Optional arguments** :class:`~mpmath.calculus.inverselaplace.FixedTalbot.calc_laplace_parameter` recognizes the following keywords *tmax* maximum time associated with vector of times (typically just the time requested) *degree* integer order of approximation (M = number of terms) *r* abscissa for `p_0` (otherwise computed using rule of thumb `2M/5`) The working precision will be increased according to a rule of thumb. If 'degree' is not specified, the working precision and degree are chosen to hopefully achieve the dps of the calling context. If 'degree' is specified, the working precision is chosen to achieve maximum resulting precision for the specified degree. .. math :: p_0=\frac{r}{t} .. math :: p_i=\frac{i r \pi}{Mt_\mathrm{max}}\left[\cot\left( \frac{i\pi}{M}\right) + j \right] \qquad 1\le i <M where `j=\sqrt{-1}`, `r=2M/5`, and `t_\mathrm{max}` is the maximum specified time. """ # required # ------------------------------ # time of desired approximation self.t = self.ctx.convert(t) # optional # ------------------------------ # maximum time desired (used for scaling) default is requested # time. self.tmax = self.ctx.convert(kwargs.get('tmax',self.t)) # empirical relationships used here based on a linear fit of # requested and delivered dps for exponentially decaying time # functions for requested dps up to 512. if 'degree' in kwargs: self.degree = kwargs['degree'] self.dps_goal = self.degree else: self.dps_goal = int(1.72*self.ctx.dps) self.degree = max(12,int(1.38*self.dps_goal)) M = self.degree # this is adjusting the dps of the calling context hopefully # the caller doesn't monkey around with it between calling # this routine and calc_time_domain_solution() self.dps_orig = self.ctx.dps self.ctx.dps = self.dps_goal # Abate & Valko rule of thumb for r parameter self.r = kwargs.get('r',self.ctx.fraction(2,5)*M) self.theta = self.ctx.linspace(0.0, self.ctx.pi, M+1) self.cot_theta = self.ctx.matrix(M,1) self.cot_theta[0] = 0 # not used # all but time-dependent part of p self.delta = self.ctx.matrix(M,1) self.delta[0] = self.r for i in range(1,M): self.cot_theta[i] = self.ctx.cot(self.theta[i]) self.delta[i] = self.r*self.theta[i]*(self.cot_theta[i] + 1j) self.p = self.ctx.matrix(M,1) self.p = self.delta/self.tmax # NB: p is complex (mpc) def calc_time_domain_solution(self,fp,t,manual_prec=False): r"""The fixed Talbot time-domain solution is computed from the Laplace-space function evaluations using .. math :: f(t,M)=\frac{2}{5t}\sum_{k=0}^{M-1}\Re \left[ \gamma_k \bar{f}(p_k)\right] where .. math :: \gamma_0 = \frac{1}{2}e^{r}\bar{f}(p_0) .. math :: \gamma_k = e^{tp_k}\left\lbrace 1 + \frac{jk\pi}{M}\left[1 + \cot \left( \frac{k \pi}{M} \right)^2 \right] - j\cot\left( \frac{k \pi}{M}\right)\right \rbrace \qquad 1\le k<M. Again, `j=\sqrt{-1}`. Before calling this function, call :class:`~mpmath.calculus.inverselaplace.FixedTalbot.calc_laplace_parameter` to set the parameters and compute the required coefficients. **References** 1. Abate, J., P. Valko (2004). Multi-precision Laplace transform inversion. *International Journal for Numerical Methods in Engineering* 60:979-993, http://dx.doi.org/10.1002/nme.995 2. Talbot, A. (1979). The accurate numerical inversion of Laplace transforms. *IMA Journal of Applied Mathematics* 23(1):97, http://dx.doi.org/10.1093/imamat/23.1.97 """ # required # ------------------------------ self.t = self.ctx.convert(t) # assume fp was computed from p matrix returned from # calc_laplace_parameter(), so is already a list or matrix of # mpmath 'mpc' types # these were computed in previous call to # calc_laplace_parameter() theta = self.theta delta = self.delta M = self.degree p = self.p r = self.r ans = self.ctx.matrix(M,1) ans[0] = self.ctx.exp(delta[0])*fp[0]/2 for i in range(1,M): ans[i] = self.ctx.exp(delta[i])*fp[i]*( 1 + 1j*theta[i]*(1 + self.cot_theta[i]**2) - 1j*self.cot_theta[i]) result = self.ctx.fraction(2,5)*self.ctx.fsum(ans)/self.t # setting dps back to value when calc_laplace_parameter was # called, unless flag is set. if not manual_prec: self.ctx.dps = self.dps_orig return result.real # **************************************** class Stehfest(InverseLaplaceTransform): def calc_laplace_parameter(self,t,**kwargs): r""" The Gaver-Stehfest method is a discrete approximation of the Widder-Post inversion algorithm, rather than a direct approximation of the Bromwich contour integral. The method abscissa along the real axis, and therefore has issues inverting oscillatory functions (which have poles in pairs away from the real axis). The working precision will be increased according to a rule of thumb. If 'degree' is not specified, the working precision and degree are chosen to hopefully achieve the dps of the calling context. If 'degree' is specified, the working precision is chosen to achieve maximum resulting precision for the specified degree. .. math :: p_k = \frac{k \log 2}{t} \qquad 1 \le k \le M """ # required # ------------------------------ # time of desired approximation self.t = self.ctx.convert(t) # optional # ------------------------------ # empirical relationships used here based on a linear fit of # requested and delivered dps for exponentially decaying time # functions for requested dps up to 512. if 'degree' in kwargs: self.degree = kwargs['degree'] self.dps_goal = int(1.38*self.degree) else: self.dps_goal = int(2.93*self.ctx.dps) self.degree = max(16,self.dps_goal) # _coeff routine requires even degree if self.degree%2 > 0: self.degree += 1 M = self.degree # this is adjusting the dps of the calling context # hopefully the caller doesn't monkey around with it # between calling this routine and calc_time_domain_solution() self.dps_orig = self.ctx.dps self.ctx.dps = self.dps_goal self.V = self._coeff() self.p = self.ctx.matrix(self.ctx.arange(1,M+1))*self.ctx.ln2/self.t # NB: p is real (mpf) def _coeff(self): r"""Salzer summation weights (aka, "Stehfest coefficients") only depend on the approximation order (M) and the precision""" M = self.degree M2 = int(M/2) # checked earlier that M is even V = self.ctx.matrix(M,1) # Salzer summation weights # get very large in magnitude and oscillate in sign, # if the precision is not high enough, there will be # catastrophic cancellation for k in range(1,M+1): z = self.ctx.matrix(min(k,M2)+1,1) for j in range(int((k+1)/2),min(k,M2)+1): z[j] = (self.ctx.power(j,M2)*self.ctx.fac(2*j)/ (self.ctx.fac(M2-j)*self.ctx.fac(j)* self.ctx.fac(j-1)*self.ctx.fac(k-j)* self.ctx.fac(2*j-k))) V[k-1] = self.ctx.power(-1,k+M2)*self.ctx.fsum(z) return V def calc_time_domain_solution(self,fp,t,manual_prec=False): r"""Compute time-domain Stehfest algorithm solution. .. math :: f(t,M) = \frac{\log 2}{t} \sum_{k=1}^{M} V_k \bar{f}\left( p_k \right) where .. math :: V_k = (-1)^{k + N/2} \sum^{\min(k,N/2)}_{i=\lfloor(k+1)/2 \rfloor} \frac{i^{\frac{N}{2}}(2i)!}{\left(\frac{N}{2}-i \right)! \, i! \, \left(i-1 \right)! \, \left(k-i\right)! \, \left(2i-k \right)!} As the degree increases, the abscissa (`p_k`) only increase linearly towards `\infty`, but the Stehfest coefficients (`V_k`) alternate in sign and increase rapidly in sign, requiring high precision to prevent overflow or loss of significance when evaluating the sum. **References** 1. Widder, D. (1941). *The Laplace Transform*. Princeton. 2. Stehfest, H. (1970). Algorithm 368: numerical inversion of Laplace transforms. *Communications of the ACM* 13(1):47-49, http://dx.doi.org/10.1145/361953.361969 """ # required self.t = self.ctx.convert(t) # assume fp was computed from p matrix returned from # calc_laplace_parameter(), so is already # a list or matrix of mpmath 'mpf' types result = self.ctx.fdot(self.V,fp)*self.ctx.ln2/self.t # setting dps back to value when calc_laplace_parameter was called if not manual_prec: self.ctx.dps = self.dps_orig # ignore any small imaginary part return result.real # **************************************** class deHoog(InverseLaplaceTransform): def calc_laplace_parameter(self,t,**kwargs): r"""the de Hoog, Knight & Stokes algorithm is an accelerated form of the Fourier series numerical inverse Laplace transform algorithms. .. math :: p_k = \gamma + \frac{jk}{T} \qquad 0 \le k < 2M+1 where .. math :: \gamma = \alpha - \frac{\log \mathrm{tol}}{2T}, `j=\sqrt{-1}`, `T = 2t_\mathrm{max}` is a scaled time, `\alpha=10^{-\mathrm{dps\_goal}}` is the real part of the rightmost pole or singularity, which is chosen based on the desired accuracy (assuming the rightmost singularity is 0), and `\mathrm{tol}=10\alpha` is the desired tolerance, which is chosen in relation to `\alpha`.` When increasing the degree, the abscissa increase towards `j\infty`, but more slowly than the fixed Talbot algorithm. The de Hoog et al. algorithm typically does better with oscillatory functions of time, and less well-behaved functions. The method tends to be slower than the Talbot and Stehfest algorithsm, especially so at very high precision (e.g., `>500` digits precision). """ # required # ------------------------------ self.t = self.ctx.convert(t) # optional # ------------------------------ self.tmax = kwargs.get('tmax',self.t) # empirical relationships used here based on a linear fit of # requested and delivered dps for exponentially decaying time # functions for requested dps up to 512. if 'degree' in kwargs: self.degree = kwargs['degree'] self.dps_goal = int(1.38*self.degree) else: self.dps_goal = int(self.ctx.dps*1.36) self.degree = max(10,self.dps_goal) # 2*M+1 terms in approximation M = self.degree # adjust alpha component of abscissa of convergence for higher # precision tmp = self.ctx.power(10.0,-self.dps_goal) self.alpha = self.ctx.convert(kwargs.get('alpha',tmp)) # desired tolerance (here simply related to alpha) self.tol = self.ctx.convert(kwargs.get('tol',self.alpha*10.0)) self.np = 2*self.degree+1 # number of terms in approximation # this is adjusting the dps of the calling context # hopefully the caller doesn't monkey around with it # between calling this routine and calc_time_domain_solution() self.dps_orig = self.ctx.dps self.ctx.dps = self.dps_goal # scaling factor (likely tun-able, but 2 is typical) self.scale = kwargs.get('scale',2) self.T = self.ctx.convert(kwargs.get('T',self.scale*self.tmax)) self.p = self.ctx.matrix(2*M+1,1) self.gamma = self.alpha - self.ctx.log(self.tol)/(self.scale*self.T) self.p = (self.gamma + self.ctx.pi* self.ctx.matrix(self.ctx.arange(self.np))/self.T*1j) # NB: p is complex (mpc) def calc_time_domain_solution(self,fp,t,manual_prec=False): r"""Calculate time-domain solution for de Hoog, Knight & Stokes algorithm. The un-accelerated Fourier series approach is: .. math :: f(t,2M+1) = \frac{e^{\gamma t}}{T} \sum_{k=0}^{2M}{}^{'} \Re\left[\bar{f}\left( p_k \right) e^{i\pi t/T} \right], where the prime on the summation indicates the first term is halved. This simplistic approach requires so many function evaluations that it is not practical. Non-linear acceleration is accomplished via Pade-approximation and an analytic expression for the remainder of the continued fraction. See the original paper (reference 2 below) a detailed description of the numerical approach. **References** 1. Davies, B. (2005). *Integral Transforms and their Applications*, Third Edition. Springer. 2. de Hoog, F., J. Knight, A. Stokes (1982). An improved method for numerical inversion of Laplace transforms. *SIAM Journal of Scientific and Statistical Computing* 3:357-366, http://dx.doi.org/10.1137/0903022 """ M = self.degree np = self.np T = self.T self.t = self.ctx.convert(t) # would it be useful to try re-using # space between e&q and A&B? e = self.ctx.zeros(np,M+1) q = self.ctx.matrix(np,M) d = self.ctx.matrix(np,1) A = self.ctx.zeros(np+2,1) B = self.ctx.ones(np+2,1) # initialize Q-D table # e[0:2*M,0] = 0.0 + 0.0j q[0,0] = fp[1]/(fp[0]/2) for i in range(1,2*M): q[i,0] = fp[i+1]/fp[i] # rhombus rule for filling triangular Q-D table (e & q) for r in range(1,M+1): # start with e, column 1, 0:2*M-2 mr = 2*(M-r) e[0:mr,r] = q[1:mr+1,r-1] - q[0:mr,r-1] + e[1:mr+1,r-1] if not r == M: rq = r+1 mr = 2*(M-rq)+1 for i in range(mr): q[i,rq-1] = q[i+1,rq-2]*e[i+1,rq-1]/e[i,rq-1] # build up continued fraction coefficients (d) d[0] = fp[0]/2 for r in range(1,M+1): d[2*r-1] = -q[0,r-1] # even terms d[2*r] = -e[0,r] # odd terms # seed A and B for recurrence #A[0] = 0.0 + 0.0j A[1] = d[0] #B[0:2] = 1.0 + 0.0j # base of the power series z = self.ctx.expjpi(self.t/T) # i*pi is already in fcn # coefficients of Pade approximation (A & B) # using recurrence for all but last term for i in range(1,2*M): A[i+1] = A[i] + d[i]*A[i-1]*z B[i+1] = B[i] + d[i]*B[i-1]*z # "improved remainder" to continued fraction brem = (1 + (d[2*M-1] - d[2*M])*z)/2 # powm1(x,y) computes x^y - 1 more accurately near zero rem = brem*self.ctx.powm1(1 + d[2*M]*z/brem, self.ctx.fraction(1,2)) # last term of recurrence using new remainder A[np] = A[2*M] + rem*A[2*M-1] B[np] = B[2*M] + rem*B[2*M-1] # diagonal Pade approximation # F=A/B represents accelerated trapezoid rule result = self.ctx.exp(self.gamma*self.t)/T*(A[np]/B[np]).real # setting dps back to value when calc_laplace_parameter was called if not manual_prec: self.ctx.dps = self.dps_orig return result # **************************************** class LaplaceTransformInversionMethods(object): def __init__(ctx, *args, **kwargs): ctx._fixed_talbot = FixedTalbot(ctx) ctx._stehfest = Stehfest(ctx) ctx._de_hoog = deHoog(ctx) def invertlaplace(ctx, f, t, **kwargs): r"""Computes the numerical inverse Laplace transform for a Laplace-space function at a given time. The function being evaluated is assumed to be a real-valued function of time. The user must supply a Laplace-space function `\bar{f}(p)`, and a desired time at which to estimate the time-domain solution `f(t)`. A few basic examples of Laplace-space functions with known inverses (see references [1,2]) : .. math :: \mathcal{L}\left\lbrace f(t) \right\rbrace=\bar{f}(p) .. math :: \mathcal{L}^{-1}\left\lbrace \bar{f}(p) \right\rbrace = f(t) .. math :: \bar{f}(p) = \frac{1}{(p+1)^2} .. math :: f(t) = t e^{-t} >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> tt = [0.001, 0.01, 0.1, 1, 10] >>> fp = lambda p: 1/(p+1)**2 >>> ft = lambda t: t*exp(-t) >>> ft(tt[0]),ft(tt[0])-invertlaplace(fp,tt[0],method='talbot') (0.000999000499833375, 8.57923043561212e-20) >>> ft(tt[1]),ft(tt[1])-invertlaplace(fp,tt[1],method='talbot') (0.00990049833749168, 3.27007646698047e-19) >>> ft(tt[2]),ft(tt[2])-invertlaplace(fp,tt[2],method='talbot') (0.090483741803596, -1.75215800052168e-18) >>> ft(tt[3]),ft(tt[3])-invertlaplace(fp,tt[3],method='talbot') (0.367879441171442, 1.2428864009344e-17) >>> ft(tt[4]),ft(tt[4])-invertlaplace(fp,tt[4],method='talbot') (0.000453999297624849, 4.04513489306658e-20) The methods also work for higher precision: >>> mp.dps = 100; mp.pretty = True >>> nstr(ft(tt[0]),15),nstr(ft(tt[0])-invertlaplace(fp,tt[0],method='talbot'),15) ('0.000999000499833375', '-4.96868310693356e-105') >>> nstr(ft(tt[1]),15),nstr(ft(tt[1])-invertlaplace(fp,tt[1],method='talbot'),15) ('0.00990049833749168', '1.23032291513122e-104') .. math :: \bar{f}(p) = \frac{1}{p^2+1} .. math :: f(t) = \mathrm{J}_0(t) >>> mp.dps = 15; mp.pretty = True >>> fp = lambda p: 1/sqrt(p*p + 1) >>> ft = lambda t: besselj(0,t) >>> ft(tt[0]),ft(tt[0])-invertlaplace(fp,tt[0]) (0.999999750000016, -8.2477943034014e-18) >>> ft(tt[1]),ft(tt[1])-invertlaplace(fp,tt[1]) (0.99997500015625, -3.69810144898872e-17) .. math :: \bar{f}(p) = \frac{\log p}{p} .. math :: f(t) = -\gamma -\log t >>> mp.dps = 15; mp.pretty = True >>> fp = lambda p: log(p)/p >>> ft = lambda t: -euler-log(t) >>> ft(tt[0]),ft(tt[0])-invertlaplace(fp,tt[0],method='stehfest') (6.3305396140806, -1.92126634837863e-16) >>> ft(tt[1]),ft(tt[1])-invertlaplace(fp,tt[1],method='stehfest') (4.02795452108656, -4.81486093200704e-16) **Options** :func:`~mpmath.invertlaplace` recognizes the following optional keywords valid for all methods: *method* Chooses numerical inverse Laplace transform algorithm (described below). *degree* Number of terms used in the approximation **Algorithms** Mpmath implements three numerical inverse Laplace transform algorithms, attributed to: Talbot, Stehfest, and de Hoog, Knight and Stokes. These can be selected by using *method='talbot'*, *method='stehfest'*, or *method='dehoog'* or by passing the classes *method=FixedTalbot*, *method=Stehfest*, or *method=deHoog*. The functions :func:`~mpmath.invlaptalbot`, :func:`~mpmath.invlapstehfest`, and :func:`~mpmath.invlapdehoog` are also available as shortcuts. All three algorithms implement a heuristic balance between the requested precision and the precision used internally for the calculations. This has been tuned for a typical exponentially decaying function and precision up to few hundred decimal digits. The Laplace transform converts the variable time (i.e., along a line) into a parameter given by the right half of the complex `p`-plane. Singularities, poles, and branch cuts in the complex `p`-plane contain all the information regarding the time behavior of the corresponding function. Any numerical method must therefore sample `p`-plane "close enough" to the singularities to accurately characterize them, while not getting too close to have catastrophic cancellation, overflow, or underflow issues. Most significantly, if one or more of the singularities in the `p`-plane is not on the left side of the Bromwich contour, its effects will be left out of the computed solution, and the answer will be completely wrong. *Talbot* The fixed Talbot method is high accuracy and fast, but the method can catastrophically fail for certain classes of time-domain behavior, including a Heaviside step function for positive time (e.g., `H(t-2)`), or some oscillatory behaviors. The Talbot method usually has adjustable parameters, but the "fixed" variety implemented here does not. This method deforms the Bromwich integral contour in the shape of a parabola towards `-\infty`, which leads to problems when the solution has a decaying exponential in it (e.g., a Heaviside step function is equivalent to multiplying by a decaying exponential in Laplace space). *Stehfest* The Stehfest algorithm only uses abscissa along the real axis of the complex `p`-plane to estimate the time-domain function. Oscillatory time-domain functions have poles away from the real axis, so this method does not work well with oscillatory functions, especially high-frequency ones. This method also depends on summation of terms in a series that grows very large, and will have catastrophic cancellation during summation if the working precision is too low. *de Hoog et al.* The de Hoog, Knight, and Stokes method is essentially a Fourier-series quadrature-type approximation to the Bromwich contour integral, with non-linear series acceleration and an analytical expression for the remainder term. This method is typically the most robust and is therefore the default method. This method also involves the greatest amount of overhead, so it is typically the slowest of the three methods at high precision. **Singularities** All numerical inverse Laplace transform methods have problems at large time when the Laplace-space function has poles, singularities, or branch cuts to the right of the origin in the complex plane. For simple poles in `\bar{f}(p)` at the `p`-plane origin, the time function is constant in time (e.g., `\mathcal{L}\left\lbrace 1 \right\rbrace=1/p` has a pole at `p=0`). A pole in `\bar{f}(p)` to the left of the origin is a decreasing function of time (e.g., `\mathcal{L}\left\lbrace e^{-t/2} \right\rbrace=1/(p+1/2)` has a pole at `p=-1/2`), and a pole to the right of the origin leads to an increasing function in time (e.g., `\mathcal{L}\left\lbrace t e^{t/4} \right\rbrace = 1/(p-1/4)^2` has a pole at `p=1/4`). When singularities occur off the real `p` axis, the time-domain function is oscillatory. For example `\mathcal{L}\left\lbrace \mathrm{J}_0(t) \right\rbrace=1/\sqrt{p^2+1}` has a branch cut starting at `p=j=\sqrt{-1}` and is a decaying oscillatory function, This range of behaviors is illustrated in Duffy [3] Figure 4.10.4, p. 228. In general as `p \rightarrow \infty` `t \rightarrow 0` and vice-versa. All numerical inverse Laplace transform methods require their abscissa to shift closer to the origin for larger times. If the abscissa shift left of the rightmost singularity in the Laplace domain, the answer will be completely wrong (the effect of singularities to the right of the Bromwich contour are not included in the results). For example, the following exponentially growing function has a pole at `p=3`: .. math :: \bar{f}(p)=\frac{1}{p^2-9} .. math :: f(t)=\frac{1}{3}\sinh 3t >>> mp.dps = 15; mp.pretty = True >>> fp = lambda p: 1/(p*p-9) >>> ft = lambda t: sinh(3*t)/3 >>> tt = [0.01,0.1,1.0,10.0] >>> ft(tt[0]),invertlaplace(fp,tt[0],method='talbot') (0.0100015000675014, 0.0100015000675014) >>> ft(tt[1]),invertlaplace(fp,tt[1],method='talbot') (0.101506764482381, 0.101506764482381) >>> ft(tt[2]),invertlaplace(fp,tt[2],method='talbot') (3.33929164246997, 3.33929164246997) >>> ft(tt[3]),invertlaplace(fp,tt[3],method='talbot') (1781079096920.74, -1.61331069624091e-14) **References** 1. [DLMF]_ section 1.14 (http://dlmf.nist.gov/1.14T4) 2. Cohen, A.M. (2007). Numerical Methods for Laplace Transform Inversion, Springer. 3. Duffy, D.G. (1998). Advanced Engineering Mathematics, CRC Press. **Numerical Inverse Laplace Transform Reviews** 1. Bellman, R., R.E. Kalaba, J.A. Lockett (1966). *Numerical inversion of the Laplace transform: Applications to Biology, Economics, Engineering, and Physics*. Elsevier. 2. Davies, B., B. Martin (1979). Numerical inversion of the Laplace transform: a survey and comparison of methods. *Journal of Computational Physics* 33:1-32, http://dx.doi.org/10.1016/0021-9991(79)90025-1 3. Duffy, D.G. (1993). On the numerical inversion of Laplace transforms: Comparison of three new methods on characteristic problems from applications. *ACM Transactions on Mathematical Software* 19(3):333-359, http://dx.doi.org/10.1145/155743.155788 4. Kuhlman, K.L., (2013). Review of Inverse Laplace Transform Algorithms for Laplace-Space Numerical Approaches, *Numerical Algorithms*, 63(2):339-355. http://dx.doi.org/10.1007/s11075-012-9625-3 """ rule = kwargs.get('method','dehoog') if type(rule) is str: lrule = rule.lower() if lrule == 'talbot': rule = ctx._fixed_talbot elif lrule == 'stehfest': rule = ctx._stehfest elif lrule == 'dehoog': rule = ctx._de_hoog else: raise ValueError("unknown invlap algorithm: %s" % rule) else: rule = rule(ctx) # determine the vector of Laplace-space parameter # needed for the requested method and desired time rule.calc_laplace_parameter(t,**kwargs) # compute the Laplace-space function evalutations # at the required abscissa. fp = [f(p) for p in rule.p] # compute the time-domain solution from the # Laplace-space function evaluations return rule.calc_time_domain_solution(fp,t) # shortcuts for the above function for specific methods def invlaptalbot(ctx, *args, **kwargs): kwargs['method'] = 'talbot' return ctx.invertlaplace(*args, **kwargs) def invlapstehfest(ctx, *args, **kwargs): kwargs['method'] = 'stehfest' return ctx.invertlaplace(*args, **kwargs) def invlapdehoog(ctx, *args, **kwargs): kwargs['method'] = 'dehoog' return ctx.invertlaplace(*args, **kwargs) # **************************************** if __name__ == '__main__': import doctest doctest.testmod()
31,135
36.558504
89
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/calculus/differentiation.py
from ..libmp.backend import xrange from .calculus import defun try: iteritems = dict.iteritems except AttributeError: iteritems = dict.items #----------------------------------------------------------------------------# # Differentiation # #----------------------------------------------------------------------------# @defun def difference(ctx, s, n): r""" Given a sequence `(s_k)` containing at least `n+1` items, returns the `n`-th forward difference, .. math :: \Delta^n = \sum_{k=0}^{\infty} (-1)^{k+n} {n \choose k} s_k. """ n = int(n) d = ctx.zero b = (-1) ** (n & 1) for k in xrange(n+1): d += b * s[k] b = (b * (k-n)) // (k+1) return d def hsteps(ctx, f, x, n, prec, **options): singular = options.get('singular') addprec = options.get('addprec', 10) direction = options.get('direction', 0) workprec = (prec+2*addprec) * (n+1) orig = ctx.prec try: ctx.prec = workprec h = options.get('h') if h is None: if options.get('relative'): hextramag = int(ctx.mag(x)) else: hextramag = 0 h = ctx.ldexp(1, -prec-addprec-hextramag) else: h = ctx.convert(h) # Directed: steps x, x+h, ... x+n*h direction = options.get('direction', 0) if direction: h *= ctx.sign(direction) steps = xrange(n+1) norm = h # Central: steps x-n*h, x-(n-2)*h ..., x, ..., x+(n-2)*h, x+n*h else: steps = xrange(-n, n+1, 2) norm = (2*h) # Perturb if singular: x += 0.5*h values = [f(x+k*h) for k in steps] return values, norm, workprec finally: ctx.prec = orig @defun def diff(ctx, f, x, n=1, **options): r""" Numerically computes the derivative of `f`, `f'(x)`, or generally for an integer `n \ge 0`, the `n`-th derivative `f^{(n)}(x)`. A few basic examples are:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> diff(lambda x: x**2 + x, 1.0) 3.0 >>> diff(lambda x: x**2 + x, 1.0, 2) 2.0 >>> diff(lambda x: x**2 + x, 1.0, 3) 0.0 >>> nprint([diff(exp, 3, n) for n in range(5)]) # exp'(x) = exp(x) [20.0855, 20.0855, 20.0855, 20.0855, 20.0855] Even more generally, given a tuple of arguments `(x_1, \ldots, x_k)` and order `(n_1, \ldots, n_k)`, the partial derivative `f^{(n_1,\ldots,n_k)}(x_1,\ldots,x_k)` is evaluated. For example:: >>> diff(lambda x,y: 3*x*y + 2*y - x, (0.25, 0.5), (0,1)) 2.75 >>> diff(lambda x,y: 3*x*y + 2*y - x, (0.25, 0.5), (1,1)) 3.0 **Options** The following optional keyword arguments are recognized: ``method`` Supported methods are ``'step'`` or ``'quad'``: derivatives may be computed using either a finite difference with a small step size `h` (default), or numerical quadrature. ``direction`` Direction of finite difference: can be -1 for a left difference, 0 for a central difference (default), or +1 for a right difference; more generally can be any complex number. ``addprec`` Extra precision for `h` used to account for the function's sensitivity to perturbations (default = 10). ``relative`` Choose `h` relative to the magnitude of `x`, rather than an absolute value; useful for large or tiny `x` (default = False). ``h`` As an alternative to ``addprec`` and ``relative``, manually select the step size `h`. ``singular`` If True, evaluation exactly at the point `x` is avoided; this is useful for differentiating functions with removable singularities. Default = False. ``radius`` Radius of integration contour (with ``method = 'quad'``). Default = 0.25. A larger radius typically is faster and more accurate, but it must be chosen so that `f` has no singularities within the radius from the evaluation point. A finite difference requires `n+1` function evaluations and must be performed at `(n+1)` times the target precision. Accordingly, `f` must support fast evaluation at high precision. With integration, a larger number of function evaluations is required, but not much extra precision is required. For high order derivatives, this method may thus be faster if f is very expensive to evaluate at high precision. **Further examples** The direction option is useful for computing left- or right-sided derivatives of nonsmooth functions:: >>> diff(abs, 0, direction=0) 0.0 >>> diff(abs, 0, direction=1) 1.0 >>> diff(abs, 0, direction=-1) -1.0 More generally, if the direction is nonzero, a right difference is computed where the step size is multiplied by sign(direction). For example, with direction=+j, the derivative from the positive imaginary direction will be computed:: >>> diff(abs, 0, direction=j) (0.0 - 1.0j) With integration, the result may have a small imaginary part even even if the result is purely real:: >>> diff(sqrt, 1, method='quad') # doctest:+ELLIPSIS (0.5 - 4.59...e-26j) >>> chop(_) 0.5 Adding precision to obtain an accurate value:: >>> diff(cos, 1e-30) 0.0 >>> diff(cos, 1e-30, h=0.0001) -9.99999998328279e-31 >>> diff(cos, 1e-30, addprec=100) -1.0e-30 """ partial = False try: orders = list(n) x = list(x) partial = True except TypeError: pass if partial: x = [ctx.convert(_) for _ in x] return _partial_diff(ctx, f, x, orders, options) method = options.get('method', 'step') if n == 0 and method != 'quad' and not options.get('singular'): return f(ctx.convert(x)) prec = ctx.prec try: if method == 'step': values, norm, workprec = hsteps(ctx, f, x, n, prec, **options) ctx.prec = workprec v = ctx.difference(values, n) / norm**n elif method == 'quad': ctx.prec += 10 radius = ctx.convert(options.get('radius', 0.25)) def g(t): rei = radius*ctx.expj(t) z = x + rei return f(z) / rei**n d = ctx.quadts(g, [0, 2*ctx.pi]) v = d * ctx.factorial(n) / (2*ctx.pi) else: raise ValueError("unknown method: %r" % method) finally: ctx.prec = prec return +v def _partial_diff(ctx, f, xs, orders, options): if not orders: return f() if not sum(orders): return f(*xs) i = 0 for i in range(len(orders)): if orders[i]: break order = orders[i] def fdiff_inner(*f_args): def inner(t): return f(*(f_args[:i] + (t,) + f_args[i+1:])) return ctx.diff(inner, f_args[i], order, **options) orders[i] = 0 return _partial_diff(ctx, fdiff_inner, xs, orders, options) @defun def diffs(ctx, f, x, n=None, **options): r""" Returns a generator that yields the sequence of derivatives .. math :: f(x), f'(x), f''(x), \ldots, f^{(k)}(x), \ldots With ``method='step'``, :func:`~mpmath.diffs` uses only `O(k)` function evaluations to generate the first `k` derivatives, rather than the roughly `O(k^2)` evaluations required if one calls :func:`~mpmath.diff` `k` separate times. With `n < \infty`, the generator stops as soon as the `n`-th derivative has been generated. If the exact number of needed derivatives is known in advance, this is further slightly more efficient. Options are the same as for :func:`~mpmath.diff`. **Examples** >>> from mpmath import * >>> mp.dps = 15 >>> nprint(list(diffs(cos, 1, 5))) [0.540302, -0.841471, -0.540302, 0.841471, 0.540302, -0.841471] >>> for i, d in zip(range(6), diffs(cos, 1)): ... print("%s %s" % (i, d)) ... 0 0.54030230586814 1 -0.841470984807897 2 -0.54030230586814 3 0.841470984807897 4 0.54030230586814 5 -0.841470984807897 """ if n is None: n = ctx.inf else: n = int(n) if options.get('method', 'step') != 'step': k = 0 while k < n + 1: yield ctx.diff(f, x, k, **options) k += 1 return singular = options.get('singular') if singular: yield ctx.diff(f, x, 0, singular=True) else: yield f(ctx.convert(x)) if n < 1: return if n == ctx.inf: A, B = 1, 2 else: A, B = 1, n+1 while 1: callprec = ctx.prec y, norm, workprec = hsteps(ctx, f, x, B, callprec, **options) for k in xrange(A, B): try: ctx.prec = workprec d = ctx.difference(y, k) / norm**k finally: ctx.prec = callprec yield +d if k >= n: return A, B = B, int(A*1.4+1) B = min(B, n) def iterable_to_function(gen): gen = iter(gen) data = [] def f(k): for i in xrange(len(data), k+1): data.append(next(gen)) return data[k] return f @defun def diffs_prod(ctx, factors): r""" Given a list of `N` iterables or generators yielding `f_k(x), f'_k(x), f''_k(x), \ldots` for `k = 1, \ldots, N`, generate `g(x), g'(x), g''(x), \ldots` where `g(x) = f_1(x) f_2(x) \cdots f_N(x)`. At high precision and for large orders, this is typically more efficient than numerical differentiation if the derivatives of each `f_k(x)` admit direct computation. Note: This function does not increase the working precision internally, so guard digits may have to be added externally for full accuracy. **Examples** >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> f = lambda x: exp(x)*cos(x)*sin(x) >>> u = diffs(f, 1) >>> v = mp.diffs_prod([diffs(exp,1), diffs(cos,1), diffs(sin,1)]) >>> next(u); next(v) 1.23586333600241 1.23586333600241 >>> next(u); next(v) 0.104658952245596 0.104658952245596 >>> next(u); next(v) -5.96999877552086 -5.96999877552086 >>> next(u); next(v) -12.4632923122697 -12.4632923122697 """ N = len(factors) if N == 1: for c in factors[0]: yield c else: u = iterable_to_function(ctx.diffs_prod(factors[:N//2])) v = iterable_to_function(ctx.diffs_prod(factors[N//2:])) n = 0 while 1: #yield sum(binomial(n,k)*u(n-k)*v(k) for k in xrange(n+1)) s = u(n) * v(0) a = 1 for k in xrange(1,n+1): a = a * (n-k+1) // k s += a * u(n-k) * v(k) yield s n += 1 def dpoly(n, _cache={}): """ nth differentiation polynomial for exp (Faa di Bruno's formula). TODO: most exponents are zero, so maybe a sparse representation would be better. """ if n in _cache: return _cache[n] if not _cache: _cache[0] = {(0,):1} R = dpoly(n-1) R = dict((c+(0,),v) for (c,v) in iteritems(R)) Ra = {} for powers, count in iteritems(R): powers1 = (powers[0]+1,) + powers[1:] if powers1 in Ra: Ra[powers1] += count else: Ra[powers1] = count for powers, count in iteritems(R): if not sum(powers): continue for k,p in enumerate(powers): if p: powers2 = powers[:k] + (p-1,powers[k+1]+1) + powers[k+2:] if powers2 in Ra: Ra[powers2] += p*count else: Ra[powers2] = p*count _cache[n] = Ra return _cache[n] @defun def diffs_exp(ctx, fdiffs): r""" Given an iterable or generator yielding `f(x), f'(x), f''(x), \ldots` generate `g(x), g'(x), g''(x), \ldots` where `g(x) = \exp(f(x))`. At high precision and for large orders, this is typically more efficient than numerical differentiation if the derivatives of `f(x)` admit direct computation. Note: This function does not increase the working precision internally, so guard digits may have to be added externally for full accuracy. **Examples** The derivatives of the gamma function can be computed using logarithmic differentiation:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> >>> def diffs_loggamma(x): ... yield loggamma(x) ... i = 0 ... while 1: ... yield psi(i,x) ... i += 1 ... >>> u = diffs_exp(diffs_loggamma(3)) >>> v = diffs(gamma, 3) >>> next(u); next(v) 2.0 2.0 >>> next(u); next(v) 1.84556867019693 1.84556867019693 >>> next(u); next(v) 2.49292999190269 2.49292999190269 >>> next(u); next(v) 3.44996501352367 3.44996501352367 """ fn = iterable_to_function(fdiffs) f0 = ctx.exp(fn(0)) yield f0 i = 1 while 1: s = ctx.mpf(0) for powers, c in iteritems(dpoly(i)): s += c*ctx.fprod(fn(k+1)**p for (k,p) in enumerate(powers) if p) yield s * f0 i += 1 @defun def differint(ctx, f, x, n=1, x0=0): r""" Calculates the Riemann-Liouville differintegral, or fractional derivative, defined by .. math :: \,_{x_0}{\mathbb{D}}^n_xf(x) = \frac{1}{\Gamma(m-n)} \frac{d^m}{dx^m} \int_{x_0}^{x}(x-t)^{m-n-1}f(t)dt where `f` is a given (presumably well-behaved) function, `x` is the evaluation point, `n` is the order, and `x_0` is the reference point of integration (`m` is an arbitrary parameter selected automatically). With `n = 1`, this is just the standard derivative `f'(x)`; with `n = 2`, the second derivative `f''(x)`, etc. With `n = -1`, it gives `\int_{x_0}^x f(t) dt`, with `n = -2` it gives `\int_{x_0}^x \left( \int_{x_0}^t f(u) du \right) dt`, etc. As `n` is permitted to be any number, this operator generalizes iterated differentiation and iterated integration to a single operator with a continuous order parameter. **Examples** There is an exact formula for the fractional derivative of a monomial `x^p`, which may be used as a reference. For example, the following gives a half-derivative (order 0.5):: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> x = mpf(3); p = 2; n = 0.5 >>> differint(lambda t: t**p, x, n) 7.81764019044672 >>> gamma(p+1)/gamma(p-n+1) * x**(p-n) 7.81764019044672 Another useful test function is the exponential function, whose integration / differentiation formula easy generalizes to arbitrary order. Here we first compute a third derivative, and then a triply nested integral. (The reference point `x_0` is set to `-\infty` to avoid nonzero endpoint terms.):: >>> differint(lambda x: exp(pi*x), -1.5, 3) 0.278538406900792 >>> exp(pi*-1.5) * pi**3 0.278538406900792 >>> differint(lambda x: exp(pi*x), 3.5, -3, -inf) 1922.50563031149 >>> exp(pi*3.5) / pi**3 1922.50563031149 However, for noninteger `n`, the differentiation formula for the exponential function must be modified to give the same result as the Riemann-Liouville differintegral:: >>> x = mpf(3.5) >>> c = pi >>> n = 1+2*j >>> differint(lambda x: exp(c*x), x, n) (-123295.005390743 + 140955.117867654j) >>> x**(-n) * exp(c)**x * (x*c)**n * gammainc(-n, 0, x*c) / gamma(-n) (-123295.005390743 + 140955.117867654j) """ m = max(int(ctx.ceil(ctx.re(n)))+1, 1) r = m-n-1 g = lambda x: ctx.quad(lambda t: (x-t)**r * f(t), [x0, x]) return ctx.diff(g, x, m) / ctx.gamma(m-n) @defun def diffun(ctx, f, n=1, **options): r""" Given a function `f`, returns a function `g(x)` that evaluates the nth derivative `f^{(n)}(x)`:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> cos2 = diffun(sin) >>> sin2 = diffun(sin, 4) >>> cos(1.3), cos2(1.3) (0.267498828624587, 0.267498828624587) >>> sin(1.3), sin2(1.3) (0.963558185417193, 0.963558185417193) The function `f` must support arbitrary precision evaluation. See :func:`~mpmath.diff` for additional details and supported keyword options. """ if n == 0: return f def g(x): return ctx.diff(f, x, n, **options) return g @defun def taylor(ctx, f, x, n, **options): r""" Produces a degree-`n` Taylor polynomial around the point `x` of the given function `f`. The coefficients are returned as a list. >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> nprint(chop(taylor(sin, 0, 5))) [0.0, 1.0, 0.0, -0.166667, 0.0, 0.00833333] The coefficients are computed using high-order numerical differentiation. The function must be possible to evaluate to arbitrary precision. See :func:`~mpmath.diff` for additional details and supported keyword options. Note that to evaluate the Taylor polynomial as an approximation of `f`, e.g. with :func:`~mpmath.polyval`, the coefficients must be reversed, and the point of the Taylor expansion must be subtracted from the argument: >>> p = taylor(exp, 2.0, 10) >>> polyval(p[::-1], 2.5 - 2.0) 12.1824939606092 >>> exp(2.5) 12.1824939607035 """ gen = enumerate(ctx.diffs(f, x, n, **options)) if options.get("chop", True): return [ctx.chop(d)/ctx.factorial(i) for i, d in gen] else: return [d/ctx.factorial(i) for i, d in gen] @defun def pade(ctx, a, L, M): r""" Computes a Pade approximation of degree `(L, M)` to a function. Given at least `L+M+1` Taylor coefficients `a` approximating a function `A(x)`, :func:`~mpmath.pade` returns coefficients of polynomials `P, Q` satisfying .. math :: P = \sum_{k=0}^L p_k x^k Q = \sum_{k=0}^M q_k x^k Q_0 = 1 A(x) Q(x) = P(x) + O(x^{L+M+1}) `P(x)/Q(x)` can provide a good approximation to an analytic function beyond the radius of convergence of its Taylor series (example from G.A. Baker 'Essentials of Pade Approximants' Academic Press, Ch.1A):: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = True >>> one = mpf(1) >>> def f(x): ... return sqrt((one + 2*x)/(one + x)) ... >>> a = taylor(f, 0, 6) >>> p, q = pade(a, 3, 3) >>> x = 10 >>> polyval(p[::-1], x)/polyval(q[::-1], x) 1.38169105566806 >>> f(x) 1.38169855941551 """ # To determine L+1 coefficients of P and M coefficients of Q # L+M+1 coefficients of A must be provided if len(a) < L+M+1: raise ValueError("L+M+1 Coefficients should be provided") if M == 0: if L == 0: return [ctx.one], [ctx.one] else: return a[:L+1], [ctx.one] # Solve first # a[L]*q[1] + ... + a[L-M+1]*q[M] = -a[L+1] # ... # a[L+M-1]*q[1] + ... + a[L]*q[M] = -a[L+M] A = ctx.matrix(M) for j in range(M): for i in range(min(M, L+j+1)): A[j, i] = a[L+j-i] v = -ctx.matrix(a[(L+1):(L+M+1)]) x = ctx.lu_solve(A, v) q = [ctx.one] + list(x) # compute p p = [0]*(L+1) for i in range(L+1): s = a[i] for j in range(1, min(M,i) + 1): s += q[j]*a[i-j] p[i] = s return p, q
20,226
30.214506
81
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_str.py
from mpmath import nstr, matrix, inf def test_nstr(): m = matrix([[0.75, 0.190940654, -0.0299195971], [0.190940654, 0.65625, 0.205663228], [-0.0299195971, 0.205663228, 0.64453125e-20]]) assert nstr(m, 4, min_fixed=-inf) == \ '''[ 0.75 0.1909 -0.02992] [ 0.1909 0.6563 0.2057] [-0.02992 0.2057 0.000000000000000000006445]''' assert nstr(m, 4) == \ '''[ 0.75 0.1909 -0.02992] [ 0.1909 0.6563 0.2057] [-0.02992 0.2057 6.445e-21]'''
544
35.333333
62
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_functions.py
from mpmath.libmp import * from mpmath import * import random import time import math import cmath def mpc_ae(a, b, eps=eps): res = True res = res and a.real.ae(b.real, eps) res = res and a.imag.ae(b.imag, eps) return res #---------------------------------------------------------------------------- # Constants and functions # tpi = "3.1415926535897932384626433832795028841971693993751058209749445923078\ 1640628620899862803482534211706798" te = "2.71828182845904523536028747135266249775724709369995957496696762772407\ 663035354759457138217852516642743" tdegree = "0.017453292519943295769236907684886127134428718885417254560971914\ 4017100911460344944368224156963450948221" teuler = "0.5772156649015328606065120900824024310421593359399235988057672348\ 84867726777664670936947063291746749516" tln2 = "0.693147180559945309417232121458176568075500134360255254120680009493\ 393621969694715605863326996418687542" tln10 = "2.30258509299404568401799145468436420760110148862877297603332790096\ 757260967735248023599720508959829834" tcatalan = "0.91596559417721901505460351493238411077414937428167213426649811\ 9621763019776254769479356512926115106249" tkhinchin = "2.6854520010653064453097148354817956938203822939944629530511523\ 4555721885953715200280114117493184769800" tglaisher = "1.2824271291006226368753425688697917277676889273250011920637400\ 2174040630885882646112973649195820237439420646" tapery = "1.2020569031595942853997381615114499907649862923404988817922715553\ 4183820578631309018645587360933525815" tphi = "1.618033988749894848204586834365638117720309179805762862135448622705\ 26046281890244970720720418939113748475" tmertens = "0.26149721284764278375542683860869585905156664826119920619206421\ 3924924510897368209714142631434246651052" ttwinprime = "0.660161815846869573927812110014555778432623360284733413319448\ 423335405642304495277143760031413839867912" def test_constants(): for prec in [3, 7, 10, 15, 20, 37, 80, 100, 29]: mp.dps = prec assert pi == mpf(tpi) assert e == mpf(te) assert degree == mpf(tdegree) assert euler == mpf(teuler) assert ln2 == mpf(tln2) assert ln10 == mpf(tln10) assert catalan == mpf(tcatalan) assert khinchin == mpf(tkhinchin) assert glaisher == mpf(tglaisher) assert phi == mpf(tphi) if prec < 50: assert mertens == mpf(tmertens) assert twinprime == mpf(ttwinprime) mp.dps = 15 assert pi >= -1 assert pi > 2 assert pi > 3 assert pi < 4 def test_exact_sqrts(): for i in range(20000): assert sqrt(mpf(i*i)) == i random.seed(1) for prec in [100, 300, 1000, 10000]: mp.dps = prec for i in range(20): A = random.randint(10**(prec//2-2), 10**(prec//2-1)) assert sqrt(mpf(A*A)) == A mp.dps = 15 for i in range(100): for a in [1, 8, 25, 112307]: assert sqrt(mpf((a*a, 2*i))) == mpf((a, i)) assert sqrt(mpf((a*a, -2*i))) == mpf((a, -i)) def test_sqrt_rounding(): for i in [2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15]: i = from_int(i) for dps in [7, 15, 83, 106, 2000]: mp.dps = dps a = mpf_pow_int(mpf_sqrt(i, mp.prec, round_down), 2, mp.prec, round_down) b = mpf_pow_int(mpf_sqrt(i, mp.prec, round_up), 2, mp.prec, round_up) assert mpf_lt(a, i) assert mpf_gt(b, i) random.seed(1234) prec = 100 for rnd in [round_down, round_nearest, round_ceiling]: for i in range(100): a = mpf_rand(prec) b = mpf_mul(a, a) assert mpf_sqrt(b, prec, rnd) == a # Test some extreme cases mp.dps = 100 a = mpf(9) + 1e-90 b = mpf(9) - 1e-90 mp.dps = 15 assert sqrt(a, rounding='d') == 3 assert sqrt(a, rounding='n') == 3 assert sqrt(a, rounding='u') > 3 assert sqrt(b, rounding='d') < 3 assert sqrt(b, rounding='n') == 3 assert sqrt(b, rounding='u') == 3 # A worst case, from the MPFR test suite assert sqrt(mpf('7.0503726185518891')) == mpf('2.655253776675949') def test_float_sqrt(): mp.dps = 15 # These should round identically for x in [0, 1e-7, 0.1, 0.5, 1, 2, 3, 4, 5, 0.333, 76.19]: assert sqrt(mpf(x)) == float(x)**0.5 assert sqrt(-1) == 1j assert sqrt(-2).ae(cmath.sqrt(-2)) assert sqrt(-3).ae(cmath.sqrt(-3)) assert sqrt(-100).ae(cmath.sqrt(-100)) assert sqrt(1j).ae(cmath.sqrt(1j)) assert sqrt(-1j).ae(cmath.sqrt(-1j)) assert sqrt(math.pi + math.e*1j).ae(cmath.sqrt(math.pi + math.e*1j)) assert sqrt(math.pi - math.e*1j).ae(cmath.sqrt(math.pi - math.e*1j)) def test_hypot(): assert hypot(0, 0) == 0 assert hypot(0, 0.33) == mpf(0.33) assert hypot(0.33, 0) == mpf(0.33) assert hypot(-0.33, 0) == mpf(0.33) assert hypot(3, 4) == mpf(5) def test_exact_cbrt(): for i in range(0, 20000, 200): assert cbrt(mpf(i*i*i)) == i random.seed(1) for prec in [100, 300, 1000, 10000]: mp.dps = prec A = random.randint(10**(prec//2-2), 10**(prec//2-1)) assert cbrt(mpf(A*A*A)) == A mp.dps = 15 def test_exp(): assert exp(0) == 1 assert exp(10000).ae(mpf('8.8068182256629215873e4342')) assert exp(-10000).ae(mpf('1.1354838653147360985e-4343')) a = exp(mpf((1, 8198646019315405, -53, 53))) assert(a.bc == bitcount(a.man)) mp.prec = 67 a = exp(mpf((1, 1781864658064754565, -60, 61))) assert(a.bc == bitcount(a.man)) mp.prec = 53 assert exp(ln2 * 10).ae(1024) assert exp(2+2j).ae(cmath.exp(2+2j)) def test_issue_73(): mp.dps = 512 a = exp(-1) b = exp(1) mp.dps = 15 assert (+a).ae(0.36787944117144233) assert (+b).ae(2.7182818284590451) def test_log(): mp.dps = 15 assert log(1) == 0 for x in [0.5, 1.5, 2.0, 3.0, 100, 10**50, 1e-50]: assert log(x).ae(math.log(x)) assert log(x, x) == 1 assert log(1024, 2) == 10 assert log(10**1234, 10) == 1234 assert log(2+2j).ae(cmath.log(2+2j)) # Accuracy near 1 assert (log(0.6+0.8j).real*10**17).ae(2.2204460492503131) assert (log(0.6-0.8j).real*10**17).ae(2.2204460492503131) assert (log(0.8-0.6j).real*10**17).ae(2.2204460492503131) assert (log(1+1e-8j).real*10**16).ae(0.5) assert (log(1-1e-8j).real*10**16).ae(0.5) assert (log(-1+1e-8j).real*10**16).ae(0.5) assert (log(-1-1e-8j).real*10**16).ae(0.5) assert (log(1j+1e-8).real*10**16).ae(0.5) assert (log(1j-1e-8).real*10**16).ae(0.5) assert (log(-1j+1e-8).real*10**16).ae(0.5) assert (log(-1j-1e-8).real*10**16).ae(0.5) assert (log(1+1e-40j).real*10**80).ae(0.5) assert (log(1j+1e-40).real*10**80).ae(0.5) # Huge assert log(ldexp(1.234,10**20)).ae(log(2)*1e20) assert log(ldexp(1.234,10**200)).ae(log(2)*1e200) # Some special values assert log(mpc(0,0)) == mpc(-inf,0) assert isnan(log(mpc(nan,0)).real) assert isnan(log(mpc(nan,0)).imag) assert isnan(log(mpc(0,nan)).real) assert isnan(log(mpc(0,nan)).imag) assert isnan(log(mpc(nan,1)).real) assert isnan(log(mpc(nan,1)).imag) assert isnan(log(mpc(1,nan)).real) assert isnan(log(mpc(1,nan)).imag) def test_trig_hyperb_basic(): for x in (list(range(100)) + list(range(-100,0))): t = x / 4.1 assert cos(mpf(t)).ae(math.cos(t)) assert sin(mpf(t)).ae(math.sin(t)) assert tan(mpf(t)).ae(math.tan(t)) assert cosh(mpf(t)).ae(math.cosh(t)) assert sinh(mpf(t)).ae(math.sinh(t)) assert tanh(mpf(t)).ae(math.tanh(t)) assert sin(1+1j).ae(cmath.sin(1+1j)) assert sin(-4-3.6j).ae(cmath.sin(-4-3.6j)) assert cos(1+1j).ae(cmath.cos(1+1j)) assert cos(-4-3.6j).ae(cmath.cos(-4-3.6j)) def test_degrees(): assert cos(0*degree) == 1 assert cos(90*degree).ae(0) assert cos(180*degree).ae(-1) assert cos(270*degree).ae(0) assert cos(360*degree).ae(1) assert sin(0*degree) == 0 assert sin(90*degree).ae(1) assert sin(180*degree).ae(0) assert sin(270*degree).ae(-1) assert sin(360*degree).ae(0) def random_complexes(N): random.seed(1) a = [] for i in range(N): x1 = random.uniform(-10, 10) y1 = random.uniform(-10, 10) x2 = random.uniform(-10, 10) y2 = random.uniform(-10, 10) z1 = complex(x1, y1) z2 = complex(x2, y2) a.append((z1, z2)) return a def test_complex_powers(): for dps in [15, 30, 100]: # Check accuracy for complex square root mp.dps = dps a = mpc(1j)**0.5 assert a.real == a.imag == mpf(2)**0.5 / 2 mp.dps = 15 random.seed(1) for (z1, z2) in random_complexes(100): assert (mpc(z1)**mpc(z2)).ae(z1**z2, 1e-12) assert (e**(-pi*1j)).ae(-1) mp.dps = 50 assert (e**(-pi*1j)).ae(-1) mp.dps = 15 def test_complex_sqrt_accuracy(): def test_mpc_sqrt(lst): for a, b in lst: z = mpc(a + j*b) assert mpc_ae(sqrt(z*z), z) z = mpc(-a + j*b) assert mpc_ae(sqrt(z*z), -z) z = mpc(a - j*b) assert mpc_ae(sqrt(z*z), z) z = mpc(-a - j*b) assert mpc_ae(sqrt(z*z), -z) random.seed(2) N = 10 mp.dps = 30 dps = mp.dps test_mpc_sqrt([(random.uniform(0, 10),random.uniform(0, 10)) for i in range(N)]) test_mpc_sqrt([(i + 0.1, (i + 0.2)*10**i) for i in range(N)]) mp.dps = 15 def test_atan(): mp.dps = 15 assert atan(-2.3).ae(math.atan(-2.3)) assert atan(1e-50) == 1e-50 assert atan(1e50).ae(pi/2) assert atan(-1e-50) == -1e-50 assert atan(-1e50).ae(-pi/2) assert atan(10**1000).ae(pi/2) for dps in [25, 70, 100, 300, 1000]: mp.dps = dps assert (4*atan(1)).ae(pi) mp.dps = 15 pi2 = pi/2 assert atan(mpc(inf,-1)).ae(pi2) assert atan(mpc(inf,0)).ae(pi2) assert atan(mpc(inf,1)).ae(pi2) assert atan(mpc(1,inf)).ae(pi2) assert atan(mpc(0,inf)).ae(pi2) assert atan(mpc(-1,inf)).ae(-pi2) assert atan(mpc(-inf,1)).ae(-pi2) assert atan(mpc(-inf,0)).ae(-pi2) assert atan(mpc(-inf,-1)).ae(-pi2) assert atan(mpc(-1,-inf)).ae(-pi2) assert atan(mpc(0,-inf)).ae(-pi2) assert atan(mpc(1,-inf)).ae(pi2) def test_atan2(): mp.dps = 15 assert atan2(1,1).ae(pi/4) assert atan2(1,-1).ae(3*pi/4) assert atan2(-1,-1).ae(-3*pi/4) assert atan2(-1,1).ae(-pi/4) assert atan2(-1,0).ae(-pi/2) assert atan2(1,0).ae(pi/2) assert atan2(0,0) == 0 assert atan2(inf,0).ae(pi/2) assert atan2(-inf,0).ae(-pi/2) assert isnan(atan2(inf,inf)) assert isnan(atan2(-inf,inf)) assert isnan(atan2(inf,-inf)) assert isnan(atan2(3,nan)) assert isnan(atan2(nan,3)) assert isnan(atan2(0,nan)) assert isnan(atan2(nan,0)) assert atan2(0,inf) == 0 assert atan2(0,-inf).ae(pi) assert atan2(10,inf) == 0 assert atan2(-10,inf) == 0 assert atan2(-10,-inf).ae(-pi) assert atan2(10,-inf).ae(pi) assert atan2(inf,10).ae(pi/2) assert atan2(inf,-10).ae(pi/2) assert atan2(-inf,10).ae(-pi/2) assert atan2(-inf,-10).ae(-pi/2) def test_areal_inverses(): assert asin(mpf(0)) == 0 assert asinh(mpf(0)) == 0 assert acosh(mpf(1)) == 0 assert isinstance(asin(mpf(0.5)), mpf) assert isinstance(asin(mpf(2.0)), mpc) assert isinstance(acos(mpf(0.5)), mpf) assert isinstance(acos(mpf(2.0)), mpc) assert isinstance(atanh(mpf(0.1)), mpf) assert isinstance(atanh(mpf(1.1)), mpc) random.seed(1) for i in range(50): x = random.uniform(0, 1) assert asin(mpf(x)).ae(math.asin(x)) assert acos(mpf(x)).ae(math.acos(x)) x = random.uniform(-10, 10) assert asinh(mpf(x)).ae(cmath.asinh(x).real) assert isinstance(asinh(mpf(x)), mpf) x = random.uniform(1, 10) assert acosh(mpf(x)).ae(cmath.acosh(x).real) assert isinstance(acosh(mpf(x)), mpf) x = random.uniform(-10, 0.999) assert isinstance(acosh(mpf(x)), mpc) x = random.uniform(-1, 1) assert atanh(mpf(x)).ae(cmath.atanh(x).real) assert isinstance(atanh(mpf(x)), mpf) dps = mp.dps mp.dps = 300 assert isinstance(asin(0.5), mpf) mp.dps = 1000 assert asin(1).ae(pi/2) assert asin(-1).ae(-pi/2) mp.dps = dps def test_invhyperb_inaccuracy(): mp.dps = 15 assert (asinh(1e-5)*10**5).ae(0.99999999998333333) assert (asinh(1e-10)*10**10).ae(1) assert (asinh(1e-50)*10**50).ae(1) assert (asinh(-1e-5)*10**5).ae(-0.99999999998333333) assert (asinh(-1e-10)*10**10).ae(-1) assert (asinh(-1e-50)*10**50).ae(-1) assert asinh(10**20).ae(46.744849040440862) assert asinh(-10**20).ae(-46.744849040440862) assert (tanh(1e-10)*10**10).ae(1) assert (tanh(-1e-10)*10**10).ae(-1) assert (atanh(1e-10)*10**10).ae(1) assert (atanh(-1e-10)*10**10).ae(-1) def test_complex_functions(): for x in (list(range(10)) + list(range(-10,0))): for y in (list(range(10)) + list(range(-10,0))): z = complex(x, y)/4.3 + 0.01j assert exp(mpc(z)).ae(cmath.exp(z)) assert log(mpc(z)).ae(cmath.log(z)) assert cos(mpc(z)).ae(cmath.cos(z)) assert sin(mpc(z)).ae(cmath.sin(z)) assert tan(mpc(z)).ae(cmath.tan(z)) assert sinh(mpc(z)).ae(cmath.sinh(z)) assert cosh(mpc(z)).ae(cmath.cosh(z)) assert tanh(mpc(z)).ae(cmath.tanh(z)) def test_complex_inverse_functions(): mp.dps = 15 iv.dps = 15 for (z1, z2) in random_complexes(30): # apparently cmath uses a different branch, so we # can't use it for comparison assert sinh(asinh(z1)).ae(z1) # assert acosh(z1).ae(cmath.acosh(z1)) assert atanh(z1).ae(cmath.atanh(z1)) assert atan(z1).ae(cmath.atan(z1)) # the reason we set a big eps here is that the cmath # functions are inaccurate assert asin(z1).ae(cmath.asin(z1), rel_eps=1e-12) assert acos(z1).ae(cmath.acos(z1), rel_eps=1e-12) one = mpf(1) for i in range(-9, 10, 3): for k in range(-9, 10, 3): a = 0.9*j*10**k + 0.8*one*10**i b = cos(acos(a)) assert b.ae(a) b = sin(asin(a)) assert b.ae(a) one = mpf(1) err = 2*10**-15 for i in range(-9, 9, 3): for k in range(-9, 9, 3): a = -0.9*10**k + j*0.8*one*10**i b = cosh(acosh(a)) assert b.ae(a, err) b = sinh(asinh(a)) assert b.ae(a, err) def test_reciprocal_functions(): assert sec(3).ae(-1.01010866590799375) assert csc(3).ae(7.08616739573718592) assert cot(3).ae(-7.01525255143453347) assert sech(3).ae(0.0993279274194332078) assert csch(3).ae(0.0998215696688227329) assert coth(3).ae(1.00496982331368917) assert asec(3).ae(1.23095941734077468) assert acsc(3).ae(0.339836909454121937) assert acot(3).ae(0.321750554396642193) assert asech(0.5).ae(1.31695789692481671) assert acsch(3).ae(0.327450150237258443) assert acoth(3).ae(0.346573590279972655) assert acot(0).ae(1.5707963267948966192) assert acoth(0).ae(1.5707963267948966192j) def test_ldexp(): mp.dps = 15 assert ldexp(mpf(2.5), 0) == 2.5 assert ldexp(mpf(2.5), -1) == 1.25 assert ldexp(mpf(2.5), 2) == 10 assert ldexp(mpf('inf'), 3) == mpf('inf') def test_frexp(): mp.dps = 15 assert frexp(0) == (0.0, 0) assert frexp(9) == (0.5625, 4) assert frexp(1) == (0.5, 1) assert frexp(0.2) == (0.8, -2) assert frexp(1000) == (0.9765625, 10) def test_aliases(): assert ln(7) == log(7) assert log10(3.75) == log(3.75,10) assert degrees(5.6) == 5.6 / degree assert radians(5.6) == 5.6 * degree assert power(-1,0.5) == j assert fmod(25,7) == 4.0 and isinstance(fmod(25,7), mpf) def test_arg_sign(): assert arg(3) == 0 assert arg(-3).ae(pi) assert arg(j).ae(pi/2) assert arg(-j).ae(-pi/2) assert arg(0) == 0 assert isnan(atan2(3,nan)) assert isnan(atan2(nan,3)) assert isnan(atan2(0,nan)) assert isnan(atan2(nan,0)) assert isnan(atan2(nan,nan)) assert arg(inf) == 0 assert arg(-inf).ae(pi) assert isnan(arg(nan)) #assert arg(inf*j).ae(pi/2) assert sign(0) == 0 assert sign(3) == 1 assert sign(-3) == -1 assert sign(inf) == 1 assert sign(-inf) == -1 assert isnan(sign(nan)) assert sign(j) == j assert sign(-3*j) == -j assert sign(1+j).ae((1+j)/sqrt(2)) def test_misc_bugs(): # test that this doesn't raise an exception mp.dps = 1000 log(1302) mp.dps = 15 def test_arange(): assert arange(10) == [mpf('0.0'), mpf('1.0'), mpf('2.0'), mpf('3.0'), mpf('4.0'), mpf('5.0'), mpf('6.0'), mpf('7.0'), mpf('8.0'), mpf('9.0')] assert arange(-5, 5) == [mpf('-5.0'), mpf('-4.0'), mpf('-3.0'), mpf('-2.0'), mpf('-1.0'), mpf('0.0'), mpf('1.0'), mpf('2.0'), mpf('3.0'), mpf('4.0')] assert arange(0, 1, 0.1) == [mpf('0.0'), mpf('0.10000000000000001'), mpf('0.20000000000000001'), mpf('0.30000000000000004'), mpf('0.40000000000000002'), mpf('0.5'), mpf('0.60000000000000009'), mpf('0.70000000000000007'), mpf('0.80000000000000004'), mpf('0.90000000000000002')] assert arange(17, -9, -3) == [mpf('17.0'), mpf('14.0'), mpf('11.0'), mpf('8.0'), mpf('5.0'), mpf('2.0'), mpf('-1.0'), mpf('-4.0'), mpf('-7.0')] assert arange(0.2, 0.1, -0.1) == [mpf('0.20000000000000001')] assert arange(0) == [] assert arange(1000, -1) == [] assert arange(-1.23, 3.21, -0.0000001) == [] def test_linspace(): assert linspace(2, 9, 7) == [mpf('2.0'), mpf('3.166666666666667'), mpf('4.3333333333333339'), mpf('5.5'), mpf('6.666666666666667'), mpf('7.8333333333333339'), mpf('9.0')] assert linspace(2, 9, 7, endpoint=0) == [mpf('2.0'), mpf('3.0'), mpf('4.0'), mpf('5.0'), mpf('6.0'), mpf('7.0'), mpf('8.0')] assert linspace(2, 7, 1) == [mpf(2)] def test_float_cbrt(): mp.dps = 30 for a in arange(0,10,0.1): assert cbrt(a*a*a).ae(a, eps) assert cbrt(-1).ae(0.5 + j*sqrt(3)/2) one_third = mpf(1)/3 for a in arange(0,10,2.7) + [0.1 + 10**5]: a = mpc(a + 1.1j) r1 = cbrt(a) mp.dps += 10 r2 = pow(a, one_third) mp.dps -= 10 assert r1.ae(r2, eps) mp.dps = 100 for n in range(100, 301, 100): w = 10**n + j*10**-3 z = w*w*w r = cbrt(z) assert mpc_ae(r, w, eps) mp.dps = 15 def test_root(): mp.dps = 30 random.seed(1) a = random.randint(0, 10000) p = a*a*a r = nthroot(mpf(p), 3) assert r == a for n in range(4, 10): p = p*a assert nthroot(mpf(p), n) == a mp.dps = 40 for n in range(10, 5000, 100): for a in [random.random()*10000, random.random()*10**100]: r = nthroot(a, n) r1 = pow(a, mpf(1)/n) assert r.ae(r1) r = nthroot(a, -n) r1 = pow(a, -mpf(1)/n) assert r.ae(r1) # XXX: this is broken right now # tests for nthroot rounding for rnd in ['nearest', 'up', 'down']: mp.rounding = rnd for n in [-5, -3, 3, 5]: prec = 50 for i in range(10): mp.prec = prec a = rand() mp.prec = 2*prec b = a**n mp.prec = prec r = nthroot(b, n) assert r == a mp.dps = 30 for n in range(3, 21): a = (random.random() + j*random.random()) assert nthroot(a, n).ae(pow(a, mpf(1)/n)) assert mpc_ae(nthroot(a, n), pow(a, mpf(1)/n)) a = (random.random()*10**100 + j*random.random()) r = nthroot(a, n) mp.dps += 4 r1 = pow(a, mpf(1)/n) mp.dps -= 4 assert r.ae(r1) assert mpc_ae(r, r1, eps) r = nthroot(a, -n) mp.dps += 4 r1 = pow(a, -mpf(1)/n) mp.dps -= 4 assert r.ae(r1) assert mpc_ae(r, r1, eps) mp.dps = 15 assert nthroot(4, 1) == 4 assert nthroot(4, 0) == 1 assert nthroot(4, -1) == 0.25 assert nthroot(inf, 1) == inf assert nthroot(inf, 2) == inf assert nthroot(inf, 3) == inf assert nthroot(inf, -1) == 0 assert nthroot(inf, -2) == 0 assert nthroot(inf, -3) == 0 assert nthroot(j, 1) == j assert nthroot(j, 0) == 1 assert nthroot(j, -1) == -j assert isnan(nthroot(nan, 1)) assert isnan(nthroot(nan, 0)) assert isnan(nthroot(nan, -1)) assert isnan(nthroot(inf, 0)) assert root(2,3) == nthroot(2,3) assert root(16,4,0) == 2 assert root(16,4,1) == 2j assert root(16,4,2) == -2 assert root(16,4,3) == -2j assert root(16,4,4) == 2 assert root(-125,3,1) == -5 def test_issue_136(): for dps in [20, 80]: mp.dps = dps r = nthroot(mpf('-1e-20'), 4) assert r.ae(mpf(10)**(-5) * (1 + j) * mpf(2)**(-0.5)) mp.dps = 80 assert nthroot('-1e-3', 4).ae(mpf(10)**(-3./4) * (1 + j)/sqrt(2)) assert nthroot('-1e-6', 4).ae((1 + j)/(10 * sqrt(20))) # Check that this doesn't take eternity to compute mp.dps = 20 assert nthroot('-1e100000000', 4).ae((1+j)*mpf('1e25000000')/sqrt(2)) mp.dps = 15 def test_mpcfun_real_imag(): mp.dps = 15 x = mpf(0.3) y = mpf(0.4) assert exp(mpc(x,0)) == exp(x) assert exp(mpc(0,y)) == mpc(cos(y),sin(y)) assert cos(mpc(x,0)) == cos(x) assert sin(mpc(x,0)) == sin(x) assert cos(mpc(0,y)) == cosh(y) assert sin(mpc(0,y)) == mpc(0,sinh(y)) assert cospi(mpc(x,0)) == cospi(x) assert sinpi(mpc(x,0)) == sinpi(x) assert cospi(mpc(0,y)).ae(cosh(pi*y)) assert sinpi(mpc(0,y)).ae(mpc(0,sinh(pi*y))) c, s = cospi_sinpi(mpc(x,0)) assert c == cospi(x) assert s == sinpi(x) c, s = cospi_sinpi(mpc(0,y)) assert c.ae(cosh(pi*y)) assert s.ae(mpc(0,sinh(pi*y))) c, s = cos_sin(mpc(x,0)) assert c == cos(x) assert s == sin(x) c, s = cos_sin(mpc(0,y)) assert c == cosh(y) assert s == mpc(0,sinh(y)) def test_perturbation_rounding(): mp.dps = 100 a = pi/10**50 b = -pi/10**50 c = 1 + a d = 1 + b mp.dps = 15 assert exp(a) == 1 assert exp(a, rounding='c') > 1 assert exp(b, rounding='c') == 1 assert exp(a, rounding='f') == 1 assert exp(b, rounding='f') < 1 assert cos(a) == 1 assert cos(a, rounding='c') == 1 assert cos(b, rounding='c') == 1 assert cos(a, rounding='f') < 1 assert cos(b, rounding='f') < 1 for f in [sin, atan, asinh, tanh]: assert f(a) == +a assert f(a, rounding='c') > a assert f(a, rounding='f') < a assert f(b) == +b assert f(b, rounding='c') > b assert f(b, rounding='f') < b for f in [asin, tan, sinh, atanh]: assert f(a) == +a assert f(b) == +b assert f(a, rounding='c') > a assert f(b, rounding='c') > b assert f(a, rounding='f') < a assert f(b, rounding='f') < b assert ln(c) == +a assert ln(d) == +b assert ln(c, rounding='c') > a assert ln(c, rounding='f') < a assert ln(d, rounding='c') > b assert ln(d, rounding='f') < b assert cosh(a) == 1 assert cosh(b) == 1 assert cosh(a, rounding='c') > 1 assert cosh(b, rounding='c') > 1 assert cosh(a, rounding='f') == 1 assert cosh(b, rounding='f') == 1 def test_integer_parts(): assert floor(3.2) == 3 assert ceil(3.2) == 4 assert floor(3.2+5j) == 3+5j assert ceil(3.2+5j) == 4+5j def test_complex_parts(): assert fabs('3') == 3 assert fabs(3+4j) == 5 assert re(3) == 3 assert re(1+4j) == 1 assert im(3) == 0 assert im(1+4j) == 4 assert conj(3) == 3 assert conj(3+4j) == 3-4j assert mpf(3).conjugate() == 3 def test_cospi_sinpi(): assert sinpi(0) == 0 assert sinpi(0.5) == 1 assert sinpi(1) == 0 assert sinpi(1.5) == -1 assert sinpi(2) == 0 assert sinpi(2.5) == 1 assert sinpi(-0.5) == -1 assert cospi(0) == 1 assert cospi(0.5) == 0 assert cospi(1) == -1 assert cospi(1.5) == 0 assert cospi(2) == 1 assert cospi(2.5) == 0 assert cospi(-0.5) == 0 assert cospi(100000000000.25).ae(sqrt(2)/2) a = cospi(2+3j) assert a.real.ae(cos((2+3j)*pi).real) assert a.imag == 0 b = sinpi(2+3j) assert b.imag.ae(sin((2+3j)*pi).imag) assert b.real == 0 mp.dps = 35 x1 = mpf(10000) - mpf('1e-15') x2 = mpf(10000) + mpf('1e-15') x3 = mpf(10000.5) - mpf('1e-15') x4 = mpf(10000.5) + mpf('1e-15') x5 = mpf(10001) - mpf('1e-15') x6 = mpf(10001) + mpf('1e-15') x7 = mpf(10001.5) - mpf('1e-15') x8 = mpf(10001.5) + mpf('1e-15') mp.dps = 15 M = 10**15 assert (sinpi(x1)*M).ae(-pi) assert (sinpi(x2)*M).ae(pi) assert (cospi(x3)*M).ae(pi) assert (cospi(x4)*M).ae(-pi) assert (sinpi(x5)*M).ae(pi) assert (sinpi(x6)*M).ae(-pi) assert (cospi(x7)*M).ae(-pi) assert (cospi(x8)*M).ae(pi) assert 0.999 < cospi(x1, rounding='d') < 1 assert 0.999 < cospi(x2, rounding='d') < 1 assert 0.999 < sinpi(x3, rounding='d') < 1 assert 0.999 < sinpi(x4, rounding='d') < 1 assert -1 < cospi(x5, rounding='d') < -0.999 assert -1 < cospi(x6, rounding='d') < -0.999 assert -1 < sinpi(x7, rounding='d') < -0.999 assert -1 < sinpi(x8, rounding='d') < -0.999 assert (sinpi(1e-15)*M).ae(pi) assert (sinpi(-1e-15)*M).ae(-pi) assert cospi(1e-15) == 1 assert cospi(1e-15, rounding='d') < 1 def test_expj(): assert expj(0) == 1 assert expj(1).ae(exp(j)) assert expj(j).ae(exp(-1)) assert expj(1+j).ae(exp(j*(1+j))) assert expjpi(0) == 1 assert expjpi(1).ae(exp(j*pi)) assert expjpi(j).ae(exp(-pi)) assert expjpi(1+j).ae(exp(j*pi*(1+j))) assert expjpi(-10**15 * j).ae('2.22579818340535731e+1364376353841841') def test_sinc(): assert sinc(0) == sincpi(0) == 1 assert sinc(inf) == sincpi(inf) == 0 assert sinc(-inf) == sincpi(-inf) == 0 assert sinc(2).ae(0.45464871341284084770) assert sinc(2+3j).ae(0.4463290318402435457-2.7539470277436474940j) assert sincpi(2) == 0 assert sincpi(1.5).ae(-0.212206590789193781) def test_fibonacci(): mp.dps = 15 assert [fibonacci(n) for n in range(-5, 10)] == \ [5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34] assert fib(2.5).ae(1.4893065462657091) assert fib(3+4j).ae(-5248.51130728372 - 14195.962288353j) assert fib(1000).ae(4.3466557686937455e+208) assert str(fib(10**100)) == '6.24499112864607e+2089876402499787337692720892375554168224592399182109535392875613974104853496745963277658556235103534' mp.dps = 2100 a = fib(10000) assert a % 10**10 == 9947366875 mp.dps = 15 assert fibonacci(inf) == inf assert fib(3+0j) == 2 def test_call_with_dps(): mp.dps = 15 assert abs(exp(1, dps=30)-e(dps=35)) < 1e-29 def test_tanh(): mp.dps = 15 assert tanh(0) == 0 assert tanh(inf) == 1 assert tanh(-inf) == -1 assert isnan(tanh(nan)) assert tanh(mpc('inf', '0')) == 1 def test_atanh(): mp.dps = 15 assert atanh(0) == 0 assert atanh(0.5).ae(0.54930614433405484570) assert atanh(-0.5).ae(-0.54930614433405484570) assert atanh(1) == inf assert atanh(-1) == -inf assert isnan(atanh(nan)) assert isinstance(atanh(1), mpf) assert isinstance(atanh(-1), mpf) # Limits at infinity jpi2 = j*pi/2 assert atanh(inf).ae(-jpi2) assert atanh(-inf).ae(jpi2) assert atanh(mpc(inf,-1)).ae(-jpi2) assert atanh(mpc(inf,0)).ae(-jpi2) assert atanh(mpc(inf,1)).ae(jpi2) assert atanh(mpc(1,inf)).ae(jpi2) assert atanh(mpc(0,inf)).ae(jpi2) assert atanh(mpc(-1,inf)).ae(jpi2) assert atanh(mpc(-inf,1)).ae(jpi2) assert atanh(mpc(-inf,0)).ae(jpi2) assert atanh(mpc(-inf,-1)).ae(-jpi2) assert atanh(mpc(-1,-inf)).ae(-jpi2) assert atanh(mpc(0,-inf)).ae(-jpi2) assert atanh(mpc(1,-inf)).ae(-jpi2) def test_expm1(): mp.dps = 15 assert expm1(0) == 0 assert expm1(3).ae(exp(3)-1) assert expm1(inf) == inf assert expm1(1e-10)*1e10 assert expm1(1e-50).ae(1e-50) assert (expm1(1e-10)*1e10).ae(1.00000000005) def test_powm1(): mp.dps = 15 assert powm1(2,3) == 7 assert powm1(-1,2) == 0 assert powm1(-1,0) == 0 assert powm1(-2,0) == 0 assert powm1(3+4j,0) == 0 assert powm1(0,1) == -1 assert powm1(0,0) == 0 assert powm1(1,0) == 0 assert powm1(1,2) == 0 assert powm1(1,3+4j) == 0 assert powm1(1,5) == 0 assert powm1(j,4) == 0 assert powm1(-j,4) == 0 assert (powm1(2,1e-100)*1e100).ae(ln2) assert powm1(2,'1e-100000000000') != 0 assert (powm1(fadd(1,1e-100,exact=True), 5)*1e100).ae(5) def test_unitroots(): assert unitroots(1) == [1] assert unitroots(2) == [1, -1] a, b, c = unitroots(3) assert a == 1 assert b.ae(-0.5 + 0.86602540378443864676j) assert c.ae(-0.5 - 0.86602540378443864676j) assert unitroots(1, primitive=True) == [1] assert unitroots(2, primitive=True) == [-1] assert unitroots(3, primitive=True) == unitroots(3)[1:] assert unitroots(4, primitive=True) == [j, -j] assert len(unitroots(17, primitive=True)) == 16 assert len(unitroots(16, primitive=True)) == 8 def test_cyclotomic(): mp.dps = 15 assert [cyclotomic(n,1) for n in range(31)] == [1,0,2,3,2,5,1,7,2,3,1,11,1,13,1,1,2,17,1,19,1,1,1,23,1,5,1,3,1,29,1] assert [cyclotomic(n,-1) for n in range(31)] == [1,-2,0,1,2,1,3,1,2,1,5,1,1,1,7,1,2,1,3,1,1,1,11,1,1,1,13,1,1,1,1] assert [cyclotomic(n,j) for n in range(21)] == [1,-1+j,1+j,j,0,1,-j,j,2,-j,1,j,3,1,-j,1,2,1,j,j,5] assert [cyclotomic(n,-j) for n in range(21)] == [1,-1-j,1-j,-j,0,1,j,-j,2,j,1,-j,3,1,j,1,2,1,-j,-j,5] assert cyclotomic(1624,j) == 1 assert cyclotomic(33600,j) == 1 u = sqrt(j, prec=500) assert cyclotomic(8, u).ae(0) assert cyclotomic(30, u).ae(5.8284271247461900976) assert cyclotomic(2040, u).ae(1) assert cyclotomic(0,2.5) == 1 assert cyclotomic(1,2.5) == 2.5-1 assert cyclotomic(2,2.5) == 2.5+1 assert cyclotomic(3,2.5) == 2.5**2 + 2.5 + 1 assert cyclotomic(7,2.5) == 406.234375
30,779
32.676149
152
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_levin.py
#!/usr/bin/python # -*- coding: utf-8 -*- from mpmath import mp from mpmath import libmp xrange = libmp.backend.xrange # Attention: # These tests run with 15-20 decimal digits precision. For higher precision the # working precision must be raised. def test_levin_0(): mp.dps = 17 eps = mp.mpf(mp.eps) with mp.extraprec(2 * mp.prec): L = mp.levin(method = "levin", variant = "u") S, s, n = [], 0, 1 while 1: s += mp.one / (n * n) n += 1 S.append(s) v, e = L.update_psum(S) if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.9 * mp.log(eps)) err = abs(v - mp.pi ** 2 / 6) assert err < eps w = mp.nsum(lambda n: 1/(n * n), [1, mp.inf], method = "levin", levin_variant = "u") err = abs(v - w) assert err < eps def test_levin_1(): mp.dps = 17 eps = mp.mpf(mp.eps) with mp.extraprec(2 * mp.prec): L = mp.levin(method = "levin", variant = "v") A, n = [], 1 while 1: s = mp.mpf(n) ** (2 + 3j) n += 1 A.append(s) v, e = L.update(A) if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.9 * mp.log(eps)) err = abs(v - mp.zeta(-2-3j)) assert err < eps w = mp.nsum(lambda n: n ** (2 + 3j), [1, mp.inf], method = "levin", levin_variant = "v") err = abs(v - w) assert err < eps def test_levin_2(): # [2] A. Sidi - "Pratical Extrapolation Methods" p.373 mp.dps = 17 z=mp.mpf(10) eps = mp.mpf(mp.eps) with mp.extraprec(2 * mp.prec): L = mp.levin(method = "sidi", variant = "t") n = 0 while 1: s = (-1)**n * mp.fac(n) * z ** (-n) v, e = L.step(s) n += 1 if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.9 * mp.log(eps)) exact = mp.quad(lambda x: mp.exp(-x)/(1+x/z),[0,mp.inf]) # there is also a symbolic expression for the integral: # exact = z * mp.exp(z) * mp.expint(1,z) err = abs(v - exact) assert err < eps w = mp.nsum(lambda n: (-1) ** n * mp.fac(n) * z ** (-n), [0, mp.inf], method = "sidi", levin_variant = "t") assert err < eps def test_levin_3(): mp.dps = 17 z=mp.mpf(2) eps = mp.mpf(mp.eps) with mp.extraprec(7*mp.prec): # we need copious amount of precision to sum this highly divergent series L = mp.levin(method = "levin", variant = "t") n, s = 0, 0 while 1: s += (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)) n += 1 v, e = L.step_psum(s) if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.8 * mp.log(eps)) exact = mp.quad(lambda x: mp.exp( -x * x / 2 - z * x ** 4), [0,mp.inf]) * 2 / mp.sqrt(2 * mp.pi) # there is also a symbolic expression for the integral: # exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi)) err = abs(v - exact) assert err < eps w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)), [0, mp.inf], method = "levin", levin_variant = "t", workprec = 8*mp.prec, steps = [2] + [1 for x in xrange(1000)]) err = abs(v - w) assert err < eps def test_levin_nsum(): mp.dps = 17 with mp.extraprec(mp.prec): z = mp.mpf(10) ** (-10) a = mp.nsum(lambda n: n**(-(1+z)), [1, mp.inf], method = "l") - 1 / z assert abs(a - mp.euler) < 1e-10 eps = mp.exp(0.8 * mp.log(mp.eps)) a = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = "sidi") assert abs(a - mp.log(2)) < eps z = 2 + 1j f = lambda n: mp.rf(2 / mp.mpf(3), n) * mp.rf(4 / mp.mpf(3), n) * z**n / (mp.rf(1 / mp.mpf(3), n) * mp.fac(n)) v = mp.nsum(f, [0, mp.inf], method = "levin", steps = [10 for x in xrange(1000)]) exact = mp.hyp2f1(2 / mp.mpf(3), 4 / mp.mpf(3), 1 / mp.mpf(3), z) assert abs(exact - v) < eps def test_cohen_alt_0(): mp.dps = 17 AC = mp.cohen_alt() S, s, n = [], 0, 1 while 1: s += -((-1) ** n) * mp.one / (n * n) n += 1 S.append(s) v, e = AC.update_psum(S) if e < mp.eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.9 * mp.log(mp.eps)) err = abs(v - mp.pi ** 2 / 12) assert err < eps def test_cohen_alt_1(): mp.dps = 17 A = [] AC = mp.cohen_alt() n = 1 while 1: A.append( mp.loggamma(1 + mp.one / (2 * n - 1))) A.append(-mp.loggamma(1 + mp.one / (2 * n))) n += 1 v, e = AC.update(A) if e < mp.eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") v = mp.exp(v) err = abs(v - 1.06215090557106) assert err < 1e-12
5,090
32.058442
206
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_gammazeta.py
from mpmath import * from mpmath.libmp import round_up, from_float, mpf_zeta_int def test_zeta_int_bug(): assert mpf_zeta_int(0, 10) == from_float(-0.5) def test_bernoulli(): assert bernfrac(0) == (1,1) assert bernfrac(1) == (-1,2) assert bernfrac(2) == (1,6) assert bernfrac(3) == (0,1) assert bernfrac(4) == (-1,30) assert bernfrac(5) == (0,1) assert bernfrac(6) == (1,42) assert bernfrac(8) == (-1,30) assert bernfrac(10) == (5,66) assert bernfrac(12) == (-691,2730) assert bernfrac(18) == (43867,798) p, q = bernfrac(228) assert p % 10**10 == 164918161 assert q == 625170 p, q = bernfrac(1000) assert p % 10**10 == 7950421099 assert q == 342999030 mp.dps = 15 assert bernoulli(0) == 1 assert bernoulli(1) == -0.5 assert bernoulli(2).ae(1./6) assert bernoulli(3) == 0 assert bernoulli(4).ae(-1./30) assert bernoulli(5) == 0 assert bernoulli(6).ae(1./42) assert str(bernoulli(10)) == '0.0757575757575758' assert str(bernoulli(234)) == '7.62772793964344e+267' assert str(bernoulli(10**5)) == '-5.82229431461335e+376755' assert str(bernoulli(10**8+2)) == '1.19570355039953e+676752584' mp.dps = 50 assert str(bernoulli(10)) == '0.075757575757575757575757575757575757575757575757576' assert str(bernoulli(234)) == '7.6277279396434392486994969020496121553385863373331e+267' assert str(bernoulli(10**5)) == '-5.8222943146133508236497045360612887555320691004308e+376755' assert str(bernoulli(10**8+2)) == '1.1957035503995297272263047884604346914602088317782e+676752584' mp.dps = 1000 assert bernoulli(10).ae(mpf(5)/66) mp.dps = 50000 assert bernoulli(10).ae(mpf(5)/66) mp.dps = 15 def test_bernpoly_eulerpoly(): mp.dps = 15 assert bernpoly(0,-1).ae(1) assert bernpoly(0,0).ae(1) assert bernpoly(0,'1/2').ae(1) assert bernpoly(0,'3/4').ae(1) assert bernpoly(0,1).ae(1) assert bernpoly(0,2).ae(1) assert bernpoly(1,-1).ae('-3/2') assert bernpoly(1,0).ae('-1/2') assert bernpoly(1,'1/2').ae(0) assert bernpoly(1,'3/4').ae('1/4') assert bernpoly(1,1).ae('1/2') assert bernpoly(1,2).ae('3/2') assert bernpoly(2,-1).ae('13/6') assert bernpoly(2,0).ae('1/6') assert bernpoly(2,'1/2').ae('-1/12') assert bernpoly(2,'3/4').ae('-1/48') assert bernpoly(2,1).ae('1/6') assert bernpoly(2,2).ae('13/6') assert bernpoly(3,-1).ae(-3) assert bernpoly(3,0).ae(0) assert bernpoly(3,'1/2').ae(0) assert bernpoly(3,'3/4').ae('-3/64') assert bernpoly(3,1).ae(0) assert bernpoly(3,2).ae(3) assert bernpoly(4,-1).ae('119/30') assert bernpoly(4,0).ae('-1/30') assert bernpoly(4,'1/2').ae('7/240') assert bernpoly(4,'3/4').ae('7/3840') assert bernpoly(4,1).ae('-1/30') assert bernpoly(4,2).ae('119/30') assert bernpoly(5,-1).ae(-5) assert bernpoly(5,0).ae(0) assert bernpoly(5,'1/2').ae(0) assert bernpoly(5,'3/4').ae('25/1024') assert bernpoly(5,1).ae(0) assert bernpoly(5,2).ae(5) assert bernpoly(10,-1).ae('665/66') assert bernpoly(10,0).ae('5/66') assert bernpoly(10,'1/2').ae('-2555/33792') assert bernpoly(10,'3/4').ae('-2555/34603008') assert bernpoly(10,1).ae('5/66') assert bernpoly(10,2).ae('665/66') assert bernpoly(11,-1).ae(-11) assert bernpoly(11,0).ae(0) assert bernpoly(11,'1/2').ae(0) assert bernpoly(11,'3/4').ae('-555731/4194304') assert bernpoly(11,1).ae(0) assert bernpoly(11,2).ae(11) assert eulerpoly(0,-1).ae(1) assert eulerpoly(0,0).ae(1) assert eulerpoly(0,'1/2').ae(1) assert eulerpoly(0,'3/4').ae(1) assert eulerpoly(0,1).ae(1) assert eulerpoly(0,2).ae(1) assert eulerpoly(1,-1).ae('-3/2') assert eulerpoly(1,0).ae('-1/2') assert eulerpoly(1,'1/2').ae(0) assert eulerpoly(1,'3/4').ae('1/4') assert eulerpoly(1,1).ae('1/2') assert eulerpoly(1,2).ae('3/2') assert eulerpoly(2,-1).ae(2) assert eulerpoly(2,0).ae(0) assert eulerpoly(2,'1/2').ae('-1/4') assert eulerpoly(2,'3/4').ae('-3/16') assert eulerpoly(2,1).ae(0) assert eulerpoly(2,2).ae(2) assert eulerpoly(3,-1).ae('-9/4') assert eulerpoly(3,0).ae('1/4') assert eulerpoly(3,'1/2').ae(0) assert eulerpoly(3,'3/4').ae('-11/64') assert eulerpoly(3,1).ae('-1/4') assert eulerpoly(3,2).ae('9/4') assert eulerpoly(4,-1).ae(2) assert eulerpoly(4,0).ae(0) assert eulerpoly(4,'1/2').ae('5/16') assert eulerpoly(4,'3/4').ae('57/256') assert eulerpoly(4,1).ae(0) assert eulerpoly(4,2).ae(2) assert eulerpoly(5,-1).ae('-3/2') assert eulerpoly(5,0).ae('-1/2') assert eulerpoly(5,'1/2').ae(0) assert eulerpoly(5,'3/4').ae('361/1024') assert eulerpoly(5,1).ae('1/2') assert eulerpoly(5,2).ae('3/2') assert eulerpoly(10,-1).ae(2) assert eulerpoly(10,0).ae(0) assert eulerpoly(10,'1/2').ae('-50521/1024') assert eulerpoly(10,'3/4').ae('-36581523/1048576') assert eulerpoly(10,1).ae(0) assert eulerpoly(10,2).ae(2) assert eulerpoly(11,-1).ae('-699/4') assert eulerpoly(11,0).ae('691/4') assert eulerpoly(11,'1/2').ae(0) assert eulerpoly(11,'3/4').ae('-512343611/4194304') assert eulerpoly(11,1).ae('-691/4') assert eulerpoly(11,2).ae('699/4') # Potential accuracy issues assert bernpoly(10000,10000).ae('5.8196915936323387117e+39999') assert bernpoly(200,17.5).ae(3.8048418524583064909e244) assert eulerpoly(200,17.5).ae(-3.7309911582655785929e275) def test_gamma(): mp.dps = 15 assert gamma(0.25).ae(3.6256099082219083119) assert gamma(0.0001).ae(9999.4228832316241908) assert gamma(300).ae('1.0201917073881354535e612') assert gamma(-0.5).ae(-3.5449077018110320546) assert gamma(-7.43).ae(0.00026524416464197007186) #assert gamma(Rational(1,2)) == gamma(0.5) #assert gamma(Rational(-7,3)).ae(gamma(mpf(-7)/3)) assert gamma(1+1j).ae(0.49801566811835604271 - 0.15494982830181068512j) assert gamma(-1+0.01j).ae(-0.422733904013474115 + 99.985883082635367436j) assert gamma(20+30j).ae(-1453876687.5534810 + 1163777777.8031573j) # Should always give exact factorials when they can # be represented as mpfs under the current working precision fact = 1 for i in range(1, 18): assert gamma(i) == fact fact *= i for dps in [170, 600]: fact = 1 mp.dps = dps for i in range(1, 105): assert gamma(i) == fact fact *= i mp.dps = 100 assert gamma(0.5).ae(sqrt(pi)) mp.dps = 15 assert factorial(0) == fac(0) == 1 assert factorial(3) == 6 assert isnan(gamma(nan)) assert gamma(1100).ae('4.8579168073569433667e2866') assert rgamma(0) == 0 assert rgamma(-1) == 0 assert rgamma(2) == 1.0 assert rgamma(3) == 0.5 assert loggamma(2+8j).ae(-8.5205176753667636926 + 10.8569497125597429366j) assert loggamma('1e10000').ae('2.302485092994045684017991e10004') assert loggamma('1e10000j').ae(mpc('-1.570796326794896619231322e10000','2.302485092994045684017991e10004')) def test_fac2(): mp.dps = 15 assert [fac2(n) for n in range(10)] == [1,1,2,3,8,15,48,105,384,945] assert fac2(-5).ae(1./3) assert fac2(-11).ae(-1./945) assert fac2(50).ae(5.20469842636666623e32) assert fac2(0.5+0.75j).ae(0.81546769394688069176-0.34901016085573266889j) assert fac2(inf) == inf assert isnan(fac2(-inf)) def test_gamma_quotients(): mp.dps = 15 h = 1e-8 ep = 1e-4 G = gamma assert gammaprod([-1],[-3,-4]) == 0 assert gammaprod([-1,0],[-5]) == inf assert abs(gammaprod([-1],[-2]) - G(-1+h)/G(-2+h)) < 1e-4 assert abs(gammaprod([-4,-3],[-2,0]) - G(-4+h)*G(-3+h)/G(-2+h)/G(0+h)) < 1e-4 assert rf(3,0) == 1 assert rf(2.5,1) == 2.5 assert rf(-5,2) == 20 assert rf(j,j).ae(gamma(2*j)/gamma(j)) assert ff(-2,0) == 1 assert ff(-2,1) == -2 assert ff(4,3) == 24 assert ff(3,4) == 0 assert binomial(0,0) == 1 assert binomial(1,0) == 1 assert binomial(0,-1) == 0 assert binomial(3,2) == 3 assert binomial(5,2) == 10 assert binomial(5,3) == 10 assert binomial(5,5) == 1 assert binomial(-1,0) == 1 assert binomial(-2,-4) == 3 assert binomial(4.5, 1.5) == 6.5625 assert binomial(1100,1) == 1100 assert binomial(1100,2) == 604450 assert beta(1,1) == 1 assert beta(0,0) == inf assert beta(3,0) == inf assert beta(-1,-1) == inf assert beta(1.5,1).ae(2/3.) assert beta(1.5,2.5).ae(pi/16) assert (10**15*beta(10,100)).ae(2.3455339739604649879) assert beta(inf,inf) == 0 assert isnan(beta(-inf,inf)) assert isnan(beta(-3,inf)) assert isnan(beta(0,inf)) assert beta(inf,0.5) == beta(0.5,inf) == 0 assert beta(inf,-1.5) == inf assert beta(inf,-0.5) == -inf assert beta(1+2j,-1-j/2).ae(1.16396542451069943086+0.08511695947832914640j) assert beta(-0.5,0.5) == 0 assert beta(-3,3).ae(-1/3.) def test_zeta(): mp.dps = 15 assert zeta(2).ae(pi**2 / 6) assert zeta(2.0).ae(pi**2 / 6) assert zeta(mpc(2)).ae(pi**2 / 6) assert zeta(100).ae(1) assert zeta(0).ae(-0.5) assert zeta(0.5).ae(-1.46035450880958681) assert zeta(-1).ae(-mpf(1)/12) assert zeta(-2) == 0 assert zeta(-3).ae(mpf(1)/120) assert zeta(-4) == 0 assert zeta(-100) == 0 assert isnan(zeta(nan)) assert zeta(1e-30).ae(-0.5) assert zeta(-1e-30).ae(-0.5) # Zeros in the critical strip assert zeta(mpc(0.5, 14.1347251417346937904)).ae(0) assert zeta(mpc(0.5, 21.0220396387715549926)).ae(0) assert zeta(mpc(0.5, 25.0108575801456887632)).ae(0) assert zeta(mpc(1e-30,1e-40)).ae(-0.5) assert zeta(mpc(-1e-30,1e-40)).ae(-0.5) mp.dps = 50 im = '236.5242296658162058024755079556629786895294952121891237' assert zeta(mpc(0.5, im)).ae(0, 1e-46) mp.dps = 15 # Complex reflection formula assert (zeta(-60+3j) / 10**34).ae(8.6270183987866146+15.337398548226238j) # issue #358 assert zeta(0,0.5) == 0 assert zeta(0,0) == 0.5 assert zeta(0,0.5,1).ae(-0.34657359027997265) def test_altzeta(): mp.dps = 15 assert altzeta(-2) == 0 assert altzeta(-4) == 0 assert altzeta(-100) == 0 assert altzeta(0) == 0.5 assert altzeta(-1) == 0.25 assert altzeta(-3) == -0.125 assert altzeta(-5) == 0.25 assert altzeta(-21) == 1180529130.25 assert altzeta(1).ae(log(2)) assert altzeta(2).ae(pi**2/12) assert altzeta(10).ae(73*pi**10/6842880) assert altzeta(50) < 1 assert altzeta(60, rounding='d') < 1 assert altzeta(60, rounding='u') == 1 assert altzeta(10000, rounding='d') < 1 assert altzeta(10000, rounding='u') == 1 assert altzeta(3+0j) == altzeta(3) s = 3+4j assert altzeta(s).ae((1-2**(1-s))*zeta(s)) s = -3+4j assert altzeta(s).ae((1-2**(1-s))*zeta(s)) assert altzeta(-100.5).ae(4.58595480083585913e+108) assert altzeta(1.3).ae(0.73821404216623045) assert altzeta(1e-30).ae(0.5) assert altzeta(-1e-30).ae(0.5) assert altzeta(mpc(1e-30,1e-40)).ae(0.5) assert altzeta(mpc(-1e-30,1e-40)).ae(0.5) def test_zeta_huge(): mp.dps = 15 assert zeta(inf) == 1 mp.dps = 50 assert zeta(100).ae('1.0000000000000000000000000000007888609052210118073522') assert zeta(40*pi).ae('1.0000000000000000000000000000000000000148407238666182') mp.dps = 10000 v = zeta(33000) mp.dps = 15 assert str(v-1) == '1.02363019598118e-9934' assert zeta(pi*1000, rounding=round_up) > 1 assert zeta(3000, rounding=round_up) > 1 assert zeta(pi*1000) == 1 assert zeta(3000) == 1 def test_zeta_negative(): mp.dps = 150 a = -pi*10**40 mp.dps = 15 assert str(zeta(a)) == '2.55880492708712e+1233536161668617575553892558646631323374078' mp.dps = 50 assert str(zeta(a)) == '2.5588049270871154960875033337384432038436330847333e+1233536161668617575553892558646631323374078' mp.dps = 15 def test_polygamma(): mp.dps = 15 psi0 = lambda z: psi(0,z) psi1 = lambda z: psi(1,z) assert psi0(3) == psi(0,3) == digamma(3) #assert psi2(3) == psi(2,3) == tetragamma(3) #assert psi3(3) == psi(3,3) == pentagamma(3) assert psi0(pi).ae(0.97721330794200673) assert psi0(-pi).ae(7.8859523853854902) assert psi0(-pi+1).ae(7.5676424992016996) assert psi0(pi+j).ae(1.04224048313859376 + 0.35853686544063749j) assert psi0(-pi-j).ae(1.3404026194821986 - 2.8824392476809402j) assert findroot(psi0, 1).ae(1.4616321449683622) assert psi0(inf) == inf assert psi1(inf) == 0 assert psi(2,inf) == 0 assert psi1(pi).ae(0.37424376965420049) assert psi1(-pi).ae(53.030438740085385) assert psi1(pi+j).ae(0.32935710377142464 - 0.12222163911221135j) assert psi1(-pi-j).ae(-0.30065008356019703 + 0.01149892486928227j) assert (10**6*psi(4,1+10*pi*j)).ae(-6.1491803479004446 - 0.3921316371664063j) assert psi0(1+10*pi*j).ae(3.4473994217222650 + 1.5548808324857071j) assert isnan(psi0(nan)) assert isnan(psi0(-inf)) assert psi0(-100.5).ae(4.615124601338064) assert psi0(3+0j).ae(psi0(3)) assert psi0(-100+3j).ae(4.6106071768714086321+3.1117510556817394626j) assert isnan(psi(2,mpc(0,inf))) assert isnan(psi(2,mpc(0,nan))) assert isnan(psi(2,mpc(0,-inf))) assert isnan(psi(2,mpc(1,inf))) assert isnan(psi(2,mpc(1,nan))) assert isnan(psi(2,mpc(1,-inf))) assert isnan(psi(2,mpc(inf,inf))) assert isnan(psi(2,mpc(nan,nan))) assert isnan(psi(2,mpc(-inf,-inf))) def test_polygamma_high_prec(): mp.dps = 100 assert str(psi(0,pi)) == "0.9772133079420067332920694864061823436408346099943256380095232865318105924777141317302075654362928734" assert str(psi(10,pi)) == "-12.98876181434889529310283769414222588307175962213707170773803550518307617769657562747174101900659238" def test_polygamma_identities(): mp.dps = 15 psi0 = lambda z: psi(0,z) psi1 = lambda z: psi(1,z) psi2 = lambda z: psi(2,z) assert psi0(0.5).ae(-euler-2*log(2)) assert psi0(1).ae(-euler) assert psi1(0.5).ae(0.5*pi**2) assert psi1(1).ae(pi**2/6) assert psi1(0.25).ae(pi**2 + 8*catalan) assert psi2(1).ae(-2*apery) mp.dps = 20 u = -182*apery+4*sqrt(3)*pi**3 mp.dps = 15 assert psi(2,5/6.).ae(u) assert psi(3,0.5).ae(pi**4) def test_foxtrot_identity(): # A test of the complex digamma function. # See http://mathworld.wolfram.com/FoxTrotSeries.html and # http://mathworld.wolfram.com/DigammaFunction.html psi0 = lambda z: psi(0,z) mp.dps = 50 a = (-1)**fraction(1,3) b = (-1)**fraction(2,3) x = -psi0(0.5*a) - psi0(-0.5*b) + psi0(0.5*(1+a)) + psi0(0.5*(1-b)) y = 2*pi*sech(0.5*sqrt(3)*pi) assert x.ae(y) mp.dps = 15 def test_polygamma_high_order(): mp.dps = 100 assert str(psi(50, pi)) == "-1344100348958402765749252447726432491812.641985273160531055707095989227897753035823152397679626136483" assert str(psi(50, pi + 14*e)) == "-0.00000000000000000189793739550804321623512073101895801993019919886375952881053090844591920308111549337295143780341396" assert str(psi(50, pi + 14*e*j)) == ("(-0.0000000000000000522516941152169248975225472155683565752375889510631513244785" "9377385233700094871256507814151956624433 - 0.00000000000000001813157041407010184" "702414110218205348527862196327980417757665282244728963891298080199341480881811613j)") mp.dps = 15 assert str(psi(50, pi)) == "-1.34410034895841e+39" assert str(psi(50, pi + 14*e)) == "-1.89793739550804e-18" assert str(psi(50, pi + 14*e*j)) == "(-5.2251694115217e-17 - 1.81315704140701e-17j)" def test_harmonic(): mp.dps = 15 assert harmonic(0) == 0 assert harmonic(1) == 1 assert harmonic(2) == 1.5 assert harmonic(3).ae(1. + 1./2 + 1./3) assert harmonic(10**10).ae(23.603066594891989701) assert harmonic(10**1000).ae(2303.162308658947) assert harmonic(0.5).ae(2-2*log(2)) assert harmonic(inf) == inf assert harmonic(2+0j) == 1.5+0j assert harmonic(1+2j).ae(1.4918071802755104+0.92080728264223022j) def test_gamma_huge_1(): mp.dps = 500 x = mpf(10**10) / 7 mp.dps = 15 assert str(gamma(x)) == "6.26075321389519e+12458010678" mp.dps = 50 assert str(gamma(x)) == "6.2607532138951929201303779291707455874010420783933e+12458010678" mp.dps = 15 def test_gamma_huge_2(): mp.dps = 500 x = mpf(10**100) / 19 mp.dps = 15 assert str(gamma(x)) == (\ "1.82341134776679e+5172997469323364168990133558175077136829182824042201886051511" "9656908623426021308685461258226190190661") mp.dps = 50 assert str(gamma(x)) == (\ "1.82341134776678875374414910350027596939980412984e+5172997469323364168990133558" "1750771368291828240422018860515119656908623426021308685461258226190190661") def test_gamma_huge_3(): mp.dps = 500 x = 10**80 // 3 + 10**70*j / 7 mp.dps = 15 y = gamma(x) assert str(y.real) == (\ "-6.82925203918106e+2636286142112569524501781477865238132302397236429627932441916" "056964386399485392600") assert str(y.imag) == (\ "8.54647143678418e+26362861421125695245017814778652381323023972364296279324419160" "56964386399485392600") mp.dps = 50 y = gamma(x) assert str(y.real) == (\ "-6.8292520391810548460682736226799637356016538421817e+26362861421125695245017814" "77865238132302397236429627932441916056964386399485392600") assert str(y.imag) == (\ "8.5464714367841748507479306948130687511711420234015e+263628614211256952450178147" "7865238132302397236429627932441916056964386399485392600") def test_gamma_huge_4(): x = 3200+11500j mp.dps = 15 assert str(gamma(x)) == \ "(8.95783268539713e+5164 - 1.94678798329735e+5164j)" mp.dps = 50 assert str(gamma(x)) == (\ "(8.9578326853971339570292952697675570822206567327092e+5164" " - 1.9467879832973509568895402139429643650329524144794e+51" "64j)") mp.dps = 15 def test_gamma_huge_5(): mp.dps = 500 x = 10**60 * j / 3 mp.dps = 15 y = gamma(x) assert str(y.real) == "-3.27753899634941e-227396058973640224580963937571892628368354580620654233316839" assert str(y.imag) == "-7.1519888950416e-227396058973640224580963937571892628368354580620654233316841" mp.dps = 50 y = gamma(x) assert str(y.real) == (\ "-3.2775389963494132168950056995974690946983219123935e-22739605897364022458096393" "7571892628368354580620654233316839") assert str(y.imag) == (\ "-7.1519888950415979749736749222530209713136588885897e-22739605897364022458096393" "7571892628368354580620654233316841") mp.dps = 15 def test_gamma_huge_6(): return mp.dps = 500 x = -10**10 + mpf(10)**(-175)*j mp.dps = 15 assert str(gamma(x)) == \ "(1.86729378905343e-95657055178 - 4.29960285282433e-95657055002j)" mp.dps = 50 assert str(gamma(x)) == (\ "(1.8672937890534298925763143275474177736153484820662e-9565705517" "8 - 4.2996028528243336966001185406200082244961757496106e-9565705" "5002j)") mp.dps = 15 def test_gamma_huge_7(): mp.dps = 100 a = 3 + j/mpf(10)**1000 mp.dps = 15 y = gamma(a) assert str(y.real) == "2.0" # wrong #assert str(y.imag) == "2.16735365342606e-1000" assert str(y.imag) == "1.84556867019693e-1000" mp.dps = 50 y = gamma(a) assert str(y.real) == "2.0" #assert str(y.imag) == "2.1673536534260596065418805612488708028522563689298e-1000" assert str(y.imag) == "1.8455686701969342787869758198351951379156813281202e-1000" def test_stieltjes(): mp.dps = 15 assert stieltjes(0).ae(+euler) mp.dps = 25 assert stieltjes(1).ae('-0.07281584548367672486058637587') assert stieltjes(2).ae('-0.009690363192872318484530386035') assert stieltjes(3).ae('0.002053834420303345866160046543') assert stieltjes(4).ae('0.002325370065467300057468170178') mp.dps = 15 assert stieltjes(1).ae(-0.07281584548367672486058637587) assert stieltjes(2).ae(-0.009690363192872318484530386035) assert stieltjes(3).ae(0.002053834420303345866160046543) assert stieltjes(4).ae(0.0023253700654673000574681701775) def test_barnesg(): mp.dps = 15 assert barnesg(0) == barnesg(-1) == 0 assert [superfac(i) for i in range(8)] == [1, 1, 2, 12, 288, 34560, 24883200, 125411328000] assert str(superfac(1000)) == '3.24570818422368e+1177245' assert isnan(barnesg(nan)) assert isnan(superfac(nan)) assert isnan(hyperfac(nan)) assert barnesg(inf) == inf assert superfac(inf) == inf assert hyperfac(inf) == inf assert isnan(superfac(-inf)) assert barnesg(0.7).ae(0.8068722730141471) assert barnesg(2+3j).ae(-0.17810213864082169+0.04504542715447838j) assert [hyperfac(n) for n in range(7)] == [1, 1, 4, 108, 27648, 86400000, 4031078400000] assert [hyperfac(n) for n in range(0,-7,-1)] == [1,1,-1,-4,108,27648,-86400000] a = barnesg(-3+0j) assert a == 0 and isinstance(a, mpc) a = hyperfac(-3+0j) assert a == -4 and isinstance(a, mpc) def test_polylog(): mp.dps = 15 zs = [mpmathify(z) for z in [0, 0.5, 0.99, 4, -0.5, -4, 1j, 3+4j]] for z in zs: assert polylog(1, z).ae(-log(1-z)) for z in zs: assert polylog(0, z).ae(z/(1-z)) for z in zs: assert polylog(-1, z).ae(z/(1-z)**2) for z in zs: assert polylog(-2, z).ae(z*(1+z)/(1-z)**3) for z in zs: assert polylog(-3, z).ae(z*(1+4*z+z**2)/(1-z)**4) assert polylog(3, 7).ae(5.3192579921456754382-5.9479244480803301023j) assert polylog(3, -7).ae(-4.5693548977219423182) assert polylog(2, 0.9).ae(1.2997147230049587252) assert polylog(2, -0.9).ae(-0.75216317921726162037) assert polylog(2, 0.9j).ae(-0.17177943786580149299+0.83598828572550503226j) assert polylog(2, 1.1).ae(1.9619991013055685931-0.2994257606855892575j) assert polylog(2, -1.1).ae(-0.89083809026228260587) assert polylog(2, 1.1*sqrt(j)).ae(0.58841571107611387722+1.09962542118827026011j) assert polylog(-2, 0.9).ae(1710) assert polylog(-2, -0.9).ae(-90/6859.) assert polylog(3, 0.9).ae(1.0496589501864398696) assert polylog(-3, 0.9).ae(48690) assert polylog(-3, -4).ae(-0.0064) assert polylog(0.5+j/3, 0.5+j/2).ae(0.31739144796565650535 + 0.99255390416556261437j) assert polylog(3+4j,1).ae(zeta(3+4j)) assert polylog(3+4j,-1).ae(-altzeta(3+4j)) def test_bell_polyexp(): mp.dps = 15 # TODO: more tests for polyexp assert (polyexp(0,1e-10)*10**10).ae(1.00000000005) assert (polyexp(1,1e-10)*10**10).ae(1.0000000001) assert polyexp(5,3j).ae(-607.7044517476176454+519.962786482001476087j) assert polyexp(-1,3.5).ae(12.09537536175543444) # bell(0,x) = 1 assert bell(0,0) == 1 assert bell(0,1) == 1 assert bell(0,2) == 1 assert bell(0,inf) == 1 assert bell(0,-inf) == 1 assert isnan(bell(0,nan)) # bell(1,x) = x assert bell(1,4) == 4 assert bell(1,0) == 0 assert bell(1,inf) == inf assert bell(1,-inf) == -inf assert isnan(bell(1,nan)) # bell(2,x) = x*(1+x) assert bell(2,-1) == 0 assert bell(2,0) == 0 # large orders / arguments assert bell(10) == 115975 assert bell(10,1) == 115975 assert bell(10, -8) == 11054008 assert bell(5,-50) == -253087550 assert bell(50,-50).ae('3.4746902914629720259e74') mp.dps = 80 assert bell(50,-50) == 347469029146297202586097646631767227177164818163463279814268368579055777450 assert bell(40,50) == 5575520134721105844739265207408344706846955281965031698187656176321717550 assert bell(74) == 5006908024247925379707076470957722220463116781409659160159536981161298714301202 mp.dps = 15 assert bell(10,20j) == 7504528595600+15649605360020j # continuity of the generalization assert bell(0.5,0).ae(sinc(pi*0.5)) def test_primezeta(): mp.dps = 15 assert primezeta(0.9).ae(1.8388316154446882243 + 3.1415926535897932385j) assert primezeta(4).ae(0.076993139764246844943) assert primezeta(1) == inf assert primezeta(inf) == 0 assert isnan(primezeta(nan)) def test_rs_zeta(): mp.dps = 15 assert zeta(0.5+100000j).ae(1.0730320148577531321 + 5.7808485443635039843j) assert zeta(0.75+100000j).ae(1.837852337251873704 + 1.9988492668661145358j) assert zeta(0.5+1000000j, derivative=3).ae(1647.7744105852674733 - 1423.1270943036622097j) assert zeta(1+1000000j, derivative=3).ae(3.4085866124523582894 - 18.179184721525947301j) assert zeta(1+1000000j, derivative=1).ae(-0.10423479366985452134 - 0.74728992803359056244j) assert zeta(0.5-1000000j, derivative=1).ae(11.636804066002521459 + 17.127254072212996004j) # Additional sanity tests using fp arithmetic. # Some more high-precision tests are found in the docstrings def ae(x, y, tol=1e-6): return abs(x-y) < tol*abs(y) assert ae(fp.zeta(0.5-100000j), 1.0730320148577531321 - 5.7808485443635039843j) assert ae(fp.zeta(0.75-100000j), 1.837852337251873704 - 1.9988492668661145358j) assert ae(fp.zeta(0.5+1e6j), 0.076089069738227100006 + 2.8051021010192989554j) assert ae(fp.zeta(0.5+1e6j, derivative=1), 11.636804066002521459 - 17.127254072212996004j) assert ae(fp.zeta(1+1e6j), 0.94738726251047891048 + 0.59421999312091832833j) assert ae(fp.zeta(1+1e6j, derivative=1), -0.10423479366985452134 - 0.74728992803359056244j) assert ae(fp.zeta(0.5+100000j, derivative=1), 10.766962036817482375 - 30.92705282105996714j) assert ae(fp.zeta(0.5+100000j, derivative=2), -119.40515625740538429 + 217.14780631141830251j) assert ae(fp.zeta(0.5+100000j, derivative=3), 1129.7550282628460881 - 1685.4736895169690346j) assert ae(fp.zeta(0.5+100000j, derivative=4), -10407.160819314958615 + 13777.786698628045085j) assert ae(fp.zeta(0.75+100000j, derivative=1), -0.41742276699594321475 - 6.4453816275049955949j) assert ae(fp.zeta(0.75+100000j, derivative=2), -9.214314279161977266 + 35.07290795337967899j) assert ae(fp.zeta(0.75+100000j, derivative=3), 110.61331857820103469 - 236.87847130518129926j) assert ae(fp.zeta(0.75+100000j, derivative=4), -1054.334275898559401 + 1769.9177890161596383j) def test_siegelz(): mp.dps = 15 assert siegelz(100000).ae(5.87959246868176504171) assert siegelz(100000, derivative=2).ae(-54.1172711010126452832) assert siegelz(100000, derivative=3).ae(-278.930831343966552538) assert siegelz(100000+j,derivative=1).ae(678.214511857070283307-379.742160779916375413j) def test_zeta_near_1(): # Test for a former bug in mpf_zeta and mpc_zeta mp.dps = 15 s1 = fadd(1, '1e-10', exact=True) s2 = fadd(1, '-1e-10', exact=True) s3 = fadd(1, '1e-10j', exact=True) assert zeta(s1).ae(1.000000000057721566490881444e10) assert zeta(s2).ae(-9.99999999942278433510574872e9) z = zeta(s3) assert z.real.ae(0.57721566490153286060) assert z.imag.ae(-9.9999999999999999999927184e9) mp.dps = 30 s1 = fadd(1, '1e-50', exact=True) s2 = fadd(1, '-1e-50', exact=True) s3 = fadd(1, '1e-50j', exact=True) assert zeta(s1).ae('1e50') assert zeta(s2).ae('-1e50') z = zeta(s3) assert z.real.ae('0.57721566490153286060651209008240243104215933593992') assert z.imag.ae('-1e50')
27,387
38.350575
159
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_pickle.py
import os import tempfile import pickle from mpmath import * def pickler(obj): fn = tempfile.mktemp() f = open(fn, 'wb') pickle.dump(obj, f) f.close() f = open(fn, 'rb') obj2 = pickle.load(f) f.close() os.remove(fn) return obj2 def test_pickle(): obj = mpf('0.5') assert obj == pickler(obj) obj = mpc('0.5','0.2') assert obj == pickler(obj)
401
13.357143
30
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_special.py
from mpmath import * def test_special(): assert inf == inf assert inf != -inf assert -inf == -inf assert inf != nan assert nan != nan assert isnan(nan) assert --inf == inf assert abs(inf) == inf assert abs(-inf) == inf assert abs(nan) != abs(nan) assert isnan(inf - inf) assert isnan(inf + (-inf)) assert isnan(-inf - (-inf)) assert isnan(inf + nan) assert isnan(-inf + nan) assert mpf(2) + inf == inf assert 2 + inf == inf assert mpf(2) - inf == -inf assert 2 - inf == -inf assert inf > 3 assert 3 < inf assert 3 > -inf assert -inf < 3 assert inf > mpf(3) assert mpf(3) < inf assert mpf(3) > -inf assert -inf < mpf(3) assert not (nan < 3) assert not (nan > 3) assert isnan(inf * 0) assert isnan(-inf * 0) assert inf * 3 == inf assert inf * -3 == -inf assert -inf * 3 == -inf assert -inf * -3 == inf assert inf * inf == inf assert -inf * -inf == inf assert isnan(nan / 3) assert inf / -3 == -inf assert inf / 3 == inf assert 3 / inf == 0 assert -3 / inf == 0 assert 0 / inf == 0 assert isnan(inf / inf) assert isnan(inf / -inf) assert isnan(inf / nan) assert mpf('inf') == mpf('+inf') == inf assert mpf('-inf') == -inf assert isnan(mpf('nan')) assert isinf(inf) assert isinf(-inf) assert not isinf(mpf(0)) assert not isinf(nan) def test_special_powers(): assert inf**3 == inf assert isnan(inf**0) assert inf**-3 == 0 assert (-inf)**2 == inf assert (-inf)**3 == -inf assert isnan((-inf)**0) assert (-inf)**-2 == 0 assert (-inf)**-3 == 0 assert isnan(nan**5) assert isnan(nan**0) def test_functions_special(): assert exp(inf) == inf assert exp(-inf) == 0 assert isnan(exp(nan)) assert log(inf) == inf assert isnan(log(nan)) assert isnan(sin(inf)) assert isnan(sin(nan)) assert atan(inf).ae(pi/2) assert atan(-inf).ae(-pi/2) assert isnan(sqrt(nan)) assert sqrt(inf) == inf def test_convert_special(): float_inf = 1e300 * 1e300 float_ninf = -float_inf float_nan = float_inf/float_ninf assert mpf(3) * float_inf == inf assert mpf(3) * float_ninf == -inf assert isnan(mpf(3) * float_nan) assert not (mpf(3) < float_nan) assert not (mpf(3) > float_nan) assert not (mpf(3) <= float_nan) assert not (mpf(3) >= float_nan) assert float(mpf('1e1000')) == float_inf assert float(mpf('-1e1000')) == float_ninf assert float(mpf('1e100000000000000000')) == float_inf assert float(mpf('-1e100000000000000000')) == float_ninf assert float(mpf('1e-100000000000000000')) == 0.0 def test_div_bug(): assert isnan(nan/1) assert isnan(nan/2) assert inf/2 == inf assert (-inf)/2 == -inf
2,848
23.991228
60
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_diff.py
from mpmath import * def test_diff(): mp.dps = 15 assert diff(log, 2.0, n=0).ae(log(2)) assert diff(cos, 1.0).ae(-sin(1)) assert diff(abs, 0.0) == 0 assert diff(abs, 0.0, direction=1) == 1 assert diff(abs, 0.0, direction=-1) == -1 assert diff(exp, 1.0).ae(e) assert diff(exp, 1.0, n=5).ae(e) assert diff(exp, 2.0, n=5, direction=3*j).ae(e**2) assert diff(lambda x: x**2, 3.0, method='quad').ae(6) assert diff(lambda x: 3+x**5, 3.0, n=2, method='quad').ae(540) assert diff(lambda x: 3+x**5, 3.0, n=2, method='step').ae(540) assert diffun(sin)(2).ae(cos(2)) assert diffun(sin, n=2)(2).ae(-sin(2)) def test_diffs(): mp.dps = 15 assert [chop(d) for d in diffs(sin, 0, 1)] == [0, 1] assert [chop(d) for d in diffs(sin, 0, 1, method='quad')] == [0, 1] assert [chop(d) for d in diffs(sin, 0, 2)] == [0, 1, 0] assert [chop(d) for d in diffs(sin, 0, 2, method='quad')] == [0, 1, 0] def test_taylor(): mp.dps = 15 # Easy to test since the coefficients are exact in floating-point assert taylor(sqrt, 1, 4) == [1, 0.5, -0.125, 0.0625, -0.0390625] def test_diff_partial(): mp.dps = 15 x,y,z = xyz = 2,3,7 f = lambda x,y,z: 3*x**2 * (y+2)**3 * z**5 assert diff(f, xyz, (0,0,0)).ae(25210500) assert diff(f, xyz, (0,0,1)).ae(18007500) assert diff(f, xyz, (0,0,2)).ae(10290000) assert diff(f, xyz, (0,1,0)).ae(15126300) assert diff(f, xyz, (0,1,1)).ae(10804500) assert diff(f, xyz, (0,1,2)).ae(6174000) assert diff(f, xyz, (0,2,0)).ae(6050520) assert diff(f, xyz, (0,2,1)).ae(4321800) assert diff(f, xyz, (0,2,2)).ae(2469600) assert diff(f, xyz, (1,0,0)).ae(25210500) assert diff(f, xyz, (1,0,1)).ae(18007500) assert diff(f, xyz, (1,0,2)).ae(10290000) assert diff(f, xyz, (1,1,0)).ae(15126300) assert diff(f, xyz, (1,1,1)).ae(10804500) assert diff(f, xyz, (1,1,2)).ae(6174000) assert diff(f, xyz, (1,2,0)).ae(6050520) assert diff(f, xyz, (1,2,1)).ae(4321800) assert diff(f, xyz, (1,2,2)).ae(2469600) assert diff(f, xyz, (2,0,0)).ae(12605250) assert diff(f, xyz, (2,0,1)).ae(9003750) assert diff(f, xyz, (2,0,2)).ae(5145000) assert diff(f, xyz, (2,1,0)).ae(7563150) assert diff(f, xyz, (2,1,1)).ae(5402250) assert diff(f, xyz, (2,1,2)).ae(3087000) assert diff(f, xyz, (2,2,0)).ae(3025260) assert diff(f, xyz, (2,2,1)).ae(2160900) assert diff(f, xyz, (2,2,2)).ae(1234800)
2,466
38.790323
74
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/torture.py
""" Torture tests for asymptotics and high precision evaluation of special functions. (Other torture tests may also be placed here.) Running this file (gmpy and psyco recommended!) takes several CPU minutes. With Python 2.6+, multiprocessing is used automatically to run tests in parallel if many cores are available. (A single test may take between a second and several minutes; possibly more.) The idea: * We evaluate functions at positive, negative, imaginary, 45- and 135-degree complex values with magnitudes between 10^-20 to 10^20, at precisions between 5 and 150 digits (we can go even higher for fast functions). * Comparing the result from two different precision levels provides a strong consistency check (particularly for functions that use different algorithms at different precision levels). * That the computation finishes at all (without failure), within reasonable time, provides a check that evaluation works at all: that the code runs, that it doesn't get stuck in an infinite loop, and that it doesn't use some extremely slowly algorithm where it could use a faster one. TODO: * Speed up those functions that take long to finish! * Generalize to test more cases; more options. * Implement a timeout mechanism. * Some functions are notably absent, including the following: * inverse trigonometric functions (some become inaccurate for complex arguments) * ci, si (not implemented properly for large complex arguments) * zeta functions (need to modify test not to try too large imaginary values) * and others... """ import sys, os from timeit import default_timer as clock if "-psyco" in sys.argv: sys.argv.remove('-psyco') import psyco psyco.full() if "-nogmpy" in sys.argv: sys.argv.remove('-nogmpy') os.environ['MPMATH_NOGMPY'] = 'Y' filt = '' if not sys.argv[-1].endswith(".py"): filt = sys.argv[-1] from mpmath import * from mpmath.libmp.backend import exec_ def test_asymp(f, maxdps=150, verbose=False, huge_range=False): dps = [5,15,25,50,90,150,500,1500,5000,10000] dps = [p for p in dps if p <= maxdps] def check(x,y,p,inpt): if abs(x-y)/abs(y) < workprec(20)(power)(10, -p+1): return print() print("Error!") print("Input:", inpt) print("dps =", p) print("Result 1:", x) print("Result 2:", y) print("Absolute error:", abs(x-y)) print("Relative error:", abs(x-y)/abs(y)) raise AssertionError exponents = range(-20,20) if huge_range: exponents += [-1000, -100, -50, 50, 100, 1000] for n in exponents: if verbose: sys.stdout.write(". ") mp.dps = 25 xpos = mpf(10)**n / 1.1287 xneg = -xpos ximag = xpos*j xcomplex1 = xpos*(1+j) xcomplex2 = xpos*(-1+j) for i in range(len(dps)): if verbose: print("Testing dps = %s" % dps[i]) mp.dps = dps[i] new = f(xpos), f(xneg), f(ximag), f(xcomplex1), f(xcomplex2) if i != 0: p = dps[i-1] check(prev[0], new[0], p, xpos) check(prev[1], new[1], p, xneg) check(prev[2], new[2], p, ximag) check(prev[3], new[3], p, xcomplex1) check(prev[4], new[4], p, xcomplex2) prev = new if verbose: print() a1, a2, a3, a4, a5 = 1.5, -2.25, 3.125, 4, 2 def test_bernoulli_huge(): p, q = bernfrac(9000) assert p % 10**10 == 9636701091 assert q == 4091851784687571609141381951327092757255270 mp.dps = 15 assert str(bernoulli(10**100)) == '-2.58183325604736e+987675256497386331227838638980680030172857347883537824464410652557820800494271520411283004120790908623' mp.dps = 50 assert str(bernoulli(10**100)) == '-2.5818332560473632073252488656039475548106223822913e+987675256497386331227838638980680030172857347883537824464410652557820800494271520411283004120790908623' mp.dps = 15 cases = """\ test_bernoulli_huge() test_asymp(lambda z: +pi, maxdps=10000) test_asymp(lambda z: +e, maxdps=10000) test_asymp(lambda z: +ln2, maxdps=10000) test_asymp(lambda z: +ln10, maxdps=10000) test_asymp(lambda z: +phi, maxdps=10000) test_asymp(lambda z: +catalan, maxdps=5000) test_asymp(lambda z: +euler, maxdps=5000) test_asymp(lambda z: +glaisher, maxdps=1000) test_asymp(lambda z: +khinchin, maxdps=1000) test_asymp(lambda z: +twinprime, maxdps=150) test_asymp(lambda z: stieltjes(2), maxdps=150) test_asymp(lambda z: +mertens, maxdps=150) test_asymp(lambda z: +apery, maxdps=5000) test_asymp(sqrt, maxdps=10000, huge_range=True) test_asymp(cbrt, maxdps=5000, huge_range=True) test_asymp(lambda z: root(z,4), maxdps=5000, huge_range=True) test_asymp(lambda z: root(z,-5), maxdps=5000, huge_range=True) test_asymp(exp, maxdps=5000, huge_range=True) test_asymp(expm1, maxdps=1500) test_asymp(ln, maxdps=5000, huge_range=True) test_asymp(cosh, maxdps=5000) test_asymp(sinh, maxdps=5000) test_asymp(tanh, maxdps=1500) test_asymp(sin, maxdps=5000, huge_range=True) test_asymp(cos, maxdps=5000, huge_range=True) test_asymp(tan, maxdps=1500) test_asymp(agm, maxdps=1500, huge_range=True) test_asymp(ellipk, maxdps=1500) test_asymp(ellipe, maxdps=1500) test_asymp(lambertw, huge_range=True) test_asymp(lambda z: lambertw(z,-1)) test_asymp(lambda z: lambertw(z,1)) test_asymp(lambda z: lambertw(z,4)) test_asymp(gamma) test_asymp(loggamma) # huge_range=True ? test_asymp(ei) test_asymp(e1) test_asymp(li, huge_range=True) test_asymp(ci) test_asymp(si) test_asymp(chi) test_asymp(shi) test_asymp(erf) test_asymp(erfc) test_asymp(erfi) test_asymp(lambda z: besselj(2, z)) test_asymp(lambda z: bessely(2, z)) test_asymp(lambda z: besseli(2, z)) test_asymp(lambda z: besselk(2, z)) test_asymp(lambda z: besselj(-2.25, z)) test_asymp(lambda z: bessely(-2.25, z)) test_asymp(lambda z: besseli(-2.25, z)) test_asymp(lambda z: besselk(-2.25, z)) test_asymp(airyai) test_asymp(airybi) test_asymp(lambda z: hyp0f1(a1, z)) test_asymp(lambda z: hyp1f1(a1, a2, z)) test_asymp(lambda z: hyp1f2(a1, a2, a3, z)) test_asymp(lambda z: hyp2f0(a1, a2, z)) test_asymp(lambda z: hyperu(a1, a2, z)) test_asymp(lambda z: hyp2f1(a1, a2, a3, z)) test_asymp(lambda z: hyp2f2(a1, a2, a3, a4, z)) test_asymp(lambda z: hyp2f3(a1, a2, a3, a4, a5, z)) test_asymp(lambda z: coulombf(a1, a2, z)) test_asymp(lambda z: coulombg(a1, a2, z)) test_asymp(lambda z: polylog(2,z)) test_asymp(lambda z: polylog(3,z)) test_asymp(lambda z: polylog(-2,z)) test_asymp(lambda z: expint(4, z)) test_asymp(lambda z: expint(-4, z)) test_asymp(lambda z: expint(2.25, z)) test_asymp(lambda z: gammainc(2.5, z, 5)) test_asymp(lambda z: gammainc(2.5, 5, z)) test_asymp(lambda z: hermite(3, z)) test_asymp(lambda z: hermite(2.5, z)) test_asymp(lambda z: legendre(3, z)) test_asymp(lambda z: legendre(4, z)) test_asymp(lambda z: legendre(2.5, z)) test_asymp(lambda z: legenp(a1, a2, z)) test_asymp(lambda z: legenq(a1, a2, z), maxdps=90) # abnormally slow test_asymp(lambda z: jtheta(1, z, 0.5)) test_asymp(lambda z: jtheta(2, z, 0.5)) test_asymp(lambda z: jtheta(3, z, 0.5)) test_asymp(lambda z: jtheta(4, z, 0.5)) test_asymp(lambda z: jtheta(1, z, 0.5, 1)) test_asymp(lambda z: jtheta(2, z, 0.5, 1)) test_asymp(lambda z: jtheta(3, z, 0.5, 1)) test_asymp(lambda z: jtheta(4, z, 0.5, 1)) test_asymp(barnesg, maxdps=90) """ def testit(line): if filt in line: print(line) t1 = clock() exec_(line, globals(), locals()) t2 = clock() elapsed = t2-t1 print("Time:", elapsed, "for", line, "(OK)") if __name__ == '__main__': try: from multiprocessing import Pool mapf = Pool(None).map print("Running tests with multiprocessing") except ImportError: print("Not using multiprocessing") mapf = map t1 = clock() tasks = cases.splitlines() mapf(testit, tasks) t2 = clock() print("Cumulative wall time:", t2-t1)
7,968
33.647826
196
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_convert.py
import random from mpmath import * from mpmath.libmp import * def test_basic_string(): """ Test basic string conversion """ mp.dps = 15 assert mpf('3') == mpf('3.0') == mpf('0003.') == mpf('0.03e2') == mpf(3.0) assert mpf('30') == mpf('30.0') == mpf('00030.') == mpf(30.0) for i in range(10): for j in range(10): assert mpf('%ie%i' % (i,j)) == i * 10**j assert str(mpf('25000.0')) == '25000.0' assert str(mpf('2500.0')) == '2500.0' assert str(mpf('250.0')) == '250.0' assert str(mpf('25.0')) == '25.0' assert str(mpf('2.5')) == '2.5' assert str(mpf('0.25')) == '0.25' assert str(mpf('0.025')) == '0.025' assert str(mpf('0.0025')) == '0.0025' assert str(mpf('0.00025')) == '0.00025' assert str(mpf('0.000025')) == '2.5e-5' assert str(mpf(0)) == '0.0' assert str(mpf('2.5e1000000000000000000000')) == '2.5e+1000000000000000000000' assert str(mpf('2.6e-1000000000000000000000')) == '2.6e-1000000000000000000000' assert str(mpf(1.23402834e-15)) == '1.23402834e-15' assert str(mpf(-1.23402834e-15)) == '-1.23402834e-15' assert str(mpf(-1.2344e-15)) == '-1.2344e-15' assert repr(mpf(-1.2344e-15)) == "mpf('-1.2343999999999999e-15')" def test_pretty(): mp.pretty = True assert repr(mpf(2.5)) == '2.5' assert repr(mpc(2.5,3.5)) == '(2.5 + 3.5j)' mp.pretty = False iv.pretty = True assert repr(mpi(2.5,3.5)) == '[2.5, 3.5]' iv.pretty = False def test_str_whitespace(): assert mpf('1.26 ') == 1.26 def test_unicode(): mp.dps = 15 try: unicode = unicode except NameError: unicode = str assert mpf(unicode('2.76')) == 2.76 assert mpf(unicode('inf')) == inf def test_str_format(): assert to_str(from_float(0.1),15,strip_zeros=False) == '0.100000000000000' assert to_str(from_float(0.0),15,show_zero_exponent=True) == '0.0e+0' assert to_str(from_float(0.0),0,show_zero_exponent=True) == '.0e+0' assert to_str(from_float(0.0),0,show_zero_exponent=False) == '.0' assert to_str(from_float(0.0),1,show_zero_exponent=True) == '0.0e+0' assert to_str(from_float(0.0),1,show_zero_exponent=False) == '0.0' assert to_str(from_float(1.23),3,show_zero_exponent=True) == '1.23e+0' assert to_str(from_float(1.23456789000000e-2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e-2' assert to_str(from_float(1.23456789000000e+2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e+2' assert to_str(from_float(2.1287e14), 15, max_fixed=1000) == '212870000000000.0' assert to_str(from_float(2.1287e15), 15, max_fixed=1000) == '2128700000000000.0' assert to_str(from_float(2.1287e16), 15, max_fixed=1000) == '21287000000000000.0' assert to_str(from_float(2.1287e30), 15, max_fixed=1000) == '2128700000000000000000000000000.0' def test_tight_string_conversion(): mp.dps = 15 # In an old version, '0.5' wasn't recognized as representing # an exact binary number and was erroneously rounded up or down assert from_str('0.5', 10, round_floor) == fhalf assert from_str('0.5', 10, round_ceiling) == fhalf def test_eval_repr_invariant(): """Test that eval(repr(x)) == x""" random.seed(123) for dps in [10, 15, 20, 50, 100]: mp.dps = dps for i in range(1000): a = mpf(random.random())**0.5 * 10**random.randint(-100, 100) assert eval(repr(a)) == a mp.dps = 15 def test_str_bugs(): mp.dps = 15 # Decimal rounding used to give the wrong exponent in some cases assert str(mpf('1e600')) == '1.0e+600' assert str(mpf('1e10000')) == '1.0e+10000' def test_str_prec0(): assert to_str(from_float(1.234), 0) == '.0e+0' assert to_str(from_float(1e-15), 0) == '.0e-15' assert to_str(from_float(1e+15), 0) == '.0e+15' assert to_str(from_float(-1e-15), 0) == '-.0e-15' assert to_str(from_float(-1e+15), 0) == '-.0e+15' def test_convert_rational(): mp.dps = 15 assert from_rational(30, 5, 53, round_nearest) == (0, 3, 1, 2) assert from_rational(-7, 4, 53, round_nearest) == (1, 7, -2, 3) assert to_rational((0, 1, -1, 1)) == (1, 2) def test_custom_class(): class mympf: @property def _mpf_(self): return mpf(3.5)._mpf_ class mympc: @property def _mpc_(self): return mpf(3.5)._mpf_, mpf(2.5)._mpf_ assert mpf(2) + mympf() == 5.5 assert mympf() + mpf(2) == 5.5 assert mpf(mympf()) == 3.5 assert mympc() + mpc(2) == mpc(5.5, 2.5) assert mpc(2) + mympc() == mpc(5.5, 2.5) assert mpc(mympc()) == (3.5+2.5j) def test_conversion_methods(): class SomethingRandom: pass class SomethingReal: def _mpmath_(self, prec, rounding): return mp.make_mpf(from_str('1.3', prec, rounding)) class SomethingComplex: def _mpmath_(self, prec, rounding): return mp.make_mpc((from_str('1.3', prec, rounding), \ from_str('1.7', prec, rounding))) x = mpf(3) z = mpc(3) a = SomethingRandom() y = SomethingReal() w = SomethingComplex() for d in [15, 45]: mp.dps = d assert (x+y).ae(mpf('4.3')) assert (y+x).ae(mpf('4.3')) assert (x+w).ae(mpc('4.3', '1.7')) assert (w+x).ae(mpc('4.3', '1.7')) assert (z+y).ae(mpc('4.3')) assert (y+z).ae(mpc('4.3')) assert (z+w).ae(mpc('4.3', '1.7')) assert (w+z).ae(mpc('4.3', '1.7')) x-y; y-x; x-w; w-x; z-y; y-z; z-w; w-z x*y; y*x; x*w; w*x; z*y; y*z; z*w; w*z x/y; y/x; x/w; w/x; z/y; y/z; z/w; w/z x**y; y**x; x**w; w**x; z**y; y**z; z**w; w**z x==y; y==x; x==w; w==x; z==y; y==z; z==w; w==z mp.dps = 15 assert x.__add__(a) is NotImplemented assert x.__radd__(a) is NotImplemented assert x.__lt__(a) is NotImplemented assert x.__gt__(a) is NotImplemented assert x.__le__(a) is NotImplemented assert x.__ge__(a) is NotImplemented assert x.__eq__(a) is NotImplemented assert x.__ne__(a) is NotImplemented # implementation detail if hasattr(x, "__cmp__"): assert x.__cmp__(a) is NotImplemented assert x.__sub__(a) is NotImplemented assert x.__rsub__(a) is NotImplemented assert x.__mul__(a) is NotImplemented assert x.__rmul__(a) is NotImplemented assert x.__div__(a) is NotImplemented assert x.__rdiv__(a) is NotImplemented assert x.__mod__(a) is NotImplemented assert x.__rmod__(a) is NotImplemented assert x.__pow__(a) is NotImplemented assert x.__rpow__(a) is NotImplemented assert z.__add__(a) is NotImplemented assert z.__radd__(a) is NotImplemented assert z.__eq__(a) is NotImplemented assert z.__ne__(a) is NotImplemented assert z.__sub__(a) is NotImplemented assert z.__rsub__(a) is NotImplemented assert z.__mul__(a) is NotImplemented assert z.__rmul__(a) is NotImplemented assert z.__div__(a) is NotImplemented assert z.__rdiv__(a) is NotImplemented assert z.__pow__(a) is NotImplemented assert z.__rpow__(a) is NotImplemented def test_mpmathify(): assert mpmathify('1/2') == 0.5 assert mpmathify('(1.0+1.0j)') == mpc(1, 1) assert mpmathify('(1.2e-10 - 3.4e5j)') == mpc('1.2e-10', '-3.4e5') assert mpmathify('1j') == mpc(1j)
7,352
37.296875
120
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_visualization.py
""" Limited tests of the visualization module. Right now it just makes sure that passing custom Axes works. """ from mpmath import mp, fp def test_axes(): try: import matplotlib version = matplotlib.__version__.split("-")[0] version = version.split(".")[:2] if [int(_) for _ in version] < [0,99]: raise ImportError import pylab except ImportError: print("\nSkipping test (pylab not available or too old version)\n") return fig = pylab.figure() axes = fig.add_subplot(111) for ctx in [mp, fp]: ctx.plot(lambda x: x**2, [0, 3], axes=axes) assert axes.get_xlabel() == 'x' assert axes.get_ylabel() == 'f(x)' fig = pylab.figure() axes = fig.add_subplot(111) for ctx in [mp, fp]: ctx.cplot(lambda z: z, [-2, 2], [-10, 10], axes=axes) assert axes.get_xlabel() == 'Re(z)' assert axes.get_ylabel() == 'Im(z)'
944
27.636364
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_ode.py
#from mpmath.calculus import ODE_step_euler, ODE_step_rk4, odeint, arange from mpmath import odefun, cos, sin, mpf, sinc, mp ''' solvers = [ODE_step_euler, ODE_step_rk4] def test_ode1(): """ Let's solve: x'' + w**2 * x = 0 i.e. x1 = x, x2 = x1': x1' = x2 x2' = -x1 """ def derivs((x1, x2), t): return x2, -x1 for solver in solvers: t = arange(0, 3.1415926, 0.005) sol = odeint(derivs, (0., 1.), t, solver) x1 = [a[0] for a in sol] x2 = [a[1] for a in sol] # the result is x1 = sin(t), x2 = cos(t) # let's just check the end points for t = pi assert abs(x1[-1]) < 1e-2 assert abs(x2[-1] - (-1)) < 1e-2 def test_ode2(): """ Let's solve: x' - x = 0 i.e. x = exp(x) """ def derivs((x), t): return x for solver in solvers: t = arange(0, 1, 1e-3) sol = odeint(derivs, (1.,), t, solver) x = [a[0] for a in sol] # the result is x = exp(t) # let's just check the end point for t = 1, i.e. x = e assert abs(x[-1] - 2.718281828) < 1e-2 ''' def test_odefun_rational(): mp.dps = 15 # A rational function f = lambda t: 1/(1+mpf(t)**2) g = odefun(lambda x, y: [-2*x*y[0]**2], 0, [f(0)]) assert f(2).ae(g(2)[0]) def test_odefun_sinc_large(): mp.dps = 15 # Sinc function; test for large x f = sinc g = odefun(lambda x, y: [(cos(x)-y[0])/x], 1, [f(1)], tol=0.01, degree=5) assert abs(f(100) - g(100)[0])/f(100) < 0.01 def test_odefun_harmonic(): mp.dps = 15 # Harmonic oscillator f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0]) for x in [0, 1, 2.5, 8, 3.7]: # we go back to 3.7 to check caching c, s = f(x) assert c.ae(cos(x)) assert s.ae(sin(x))
1,822
23.635135
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_compatibility.py
from mpmath import * from random import seed, randint, random import math # Test compatibility with Python floats, which are # IEEE doubles (53-bit) N = 5000 seed(1) # Choosing exponents between roughly -140, 140 ensures that # the Python floats don't overflow or underflow xs = [(random()-1) * 10**randint(-140, 140) for x in range(N)] ys = [(random()-1) * 10**randint(-140, 140) for x in range(N)] # include some equal values ys[int(N*0.8):] = xs[int(N*0.8):] # Detect whether Python is compiled to use 80-bit floating-point # instructions, in which case the double compatibility test breaks uses_x87 = -4.1974624032366689e+117 / -8.4657370748010221e-47 \ == 4.9581771393902231e+163 def test_double_compatibility(): mp.prec = 53 for x, y in zip(xs, ys): mpx = mpf(x) mpy = mpf(y) assert mpf(x) == x assert (mpx < mpy) == (x < y) assert (mpx > mpy) == (x > y) assert (mpx == mpy) == (x == y) assert (mpx != mpy) == (x != y) assert (mpx <= mpy) == (x <= y) assert (mpx >= mpy) == (x >= y) assert mpx == mpx if uses_x87: mp.prec = 64 a = mpx + mpy b = mpx * mpy c = mpx / mpy d = mpx % mpy mp.prec = 53 assert +a == x + y assert +b == x * y assert +c == x / y assert +d == x % y else: assert mpx + mpy == x + y assert mpx * mpy == x * y assert mpx / mpy == x / y assert mpx % mpy == x % y assert abs(mpx) == abs(x) assert mpf(repr(x)) == x assert ceil(mpx) == math.ceil(x) assert floor(mpx) == math.floor(x) def test_sqrt(): # this fails quite often. it appers to be float # that rounds the wrong way, not mpf fail = 0 mp.prec = 53 for x in xs: x = abs(x) mp.prec = 100 mp_high = mpf(x)**0.5 mp.prec = 53 mp_low = mpf(x)**0.5 fp = x**0.5 assert abs(mp_low-mp_high) <= abs(fp-mp_high) fail += mp_low != fp assert fail < N/10 def test_bugs(): # particular bugs assert mpf(4.4408920985006262E-16) < mpf(1.7763568394002505E-15) assert mpf(-4.4408920985006262E-16) > mpf(-1.7763568394002505E-15)
2,306
28.576923
70
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_bitwise.py
""" Test bit-level integer and mpf operations """ from mpmath import * from mpmath.libmp import * def test_bitcount(): assert bitcount(0) == 0 assert bitcount(1) == 1 assert bitcount(7) == 3 assert bitcount(8) == 4 assert bitcount(2**100) == 101 assert bitcount(2**100-1) == 100 def test_trailing(): assert trailing(0) == 0 assert trailing(1) == 0 assert trailing(2) == 1 assert trailing(7) == 0 assert trailing(8) == 3 assert trailing(2**100) == 100 assert trailing(2**100-1) == 0 def test_round_down(): assert from_man_exp(0, -4, 4, round_down)[:3] == (0, 0, 0) assert from_man_exp(0xf0, -4, 4, round_down)[:3] == (0, 15, 0) assert from_man_exp(0xf1, -4, 4, round_down)[:3] == (0, 15, 0) assert from_man_exp(0xff, -4, 4, round_down)[:3] == (0, 15, 0) assert from_man_exp(-0xf0, -4, 4, round_down)[:3] == (1, 15, 0) assert from_man_exp(-0xf1, -4, 4, round_down)[:3] == (1, 15, 0) assert from_man_exp(-0xff, -4, 4, round_down)[:3] == (1, 15, 0) def test_round_up(): assert from_man_exp(0, -4, 4, round_up)[:3] == (0, 0, 0) assert from_man_exp(0xf0, -4, 4, round_up)[:3] == (0, 15, 0) assert from_man_exp(0xf1, -4, 4, round_up)[:3] == (0, 1, 4) assert from_man_exp(0xff, -4, 4, round_up)[:3] == (0, 1, 4) assert from_man_exp(-0xf0, -4, 4, round_up)[:3] == (1, 15, 0) assert from_man_exp(-0xf1, -4, 4, round_up)[:3] == (1, 1, 4) assert from_man_exp(-0xff, -4, 4, round_up)[:3] == (1, 1, 4) def test_round_floor(): assert from_man_exp(0, -4, 4, round_floor)[:3] == (0, 0, 0) assert from_man_exp(0xf0, -4, 4, round_floor)[:3] == (0, 15, 0) assert from_man_exp(0xf1, -4, 4, round_floor)[:3] == (0, 15, 0) assert from_man_exp(0xff, -4, 4, round_floor)[:3] == (0, 15, 0) assert from_man_exp(-0xf0, -4, 4, round_floor)[:3] == (1, 15, 0) assert from_man_exp(-0xf1, -4, 4, round_floor)[:3] == (1, 1, 4) assert from_man_exp(-0xff, -4, 4, round_floor)[:3] == (1, 1, 4) def test_round_ceiling(): assert from_man_exp(0, -4, 4, round_ceiling)[:3] == (0, 0, 0) assert from_man_exp(0xf0, -4, 4, round_ceiling)[:3] == (0, 15, 0) assert from_man_exp(0xf1, -4, 4, round_ceiling)[:3] == (0, 1, 4) assert from_man_exp(0xff, -4, 4, round_ceiling)[:3] == (0, 1, 4) assert from_man_exp(-0xf0, -4, 4, round_ceiling)[:3] == (1, 15, 0) assert from_man_exp(-0xf1, -4, 4, round_ceiling)[:3] == (1, 15, 0) assert from_man_exp(-0xff, -4, 4, round_ceiling)[:3] == (1, 15, 0) def test_round_nearest(): assert from_man_exp(0, -4, 4, round_nearest)[:3] == (0, 0, 0) assert from_man_exp(0xf0, -4, 4, round_nearest)[:3] == (0, 15, 0) assert from_man_exp(0xf7, -4, 4, round_nearest)[:3] == (0, 15, 0) assert from_man_exp(0xf8, -4, 4, round_nearest)[:3] == (0, 1, 4) # 1111.1000 -> 10000.0 assert from_man_exp(0xf9, -4, 4, round_nearest)[:3] == (0, 1, 4) # 1111.1001 -> 10000.0 assert from_man_exp(0xe8, -4, 4, round_nearest)[:3] == (0, 7, 1) # 1110.1000 -> 1110.0 assert from_man_exp(0xe9, -4, 4, round_nearest)[:3] == (0, 15, 0) # 1110.1001 -> 1111.0 assert from_man_exp(-0xf0, -4, 4, round_nearest)[:3] == (1, 15, 0) assert from_man_exp(-0xf7, -4, 4, round_nearest)[:3] == (1, 15, 0) assert from_man_exp(-0xf8, -4, 4, round_nearest)[:3] == (1, 1, 4) assert from_man_exp(-0xf9, -4, 4, round_nearest)[:3] == (1, 1, 4) assert from_man_exp(-0xe8, -4, 4, round_nearest)[:3] == (1, 7, 1) assert from_man_exp(-0xe9, -4, 4, round_nearest)[:3] == (1, 15, 0) def test_rounding_bugs(): # 1 less than power-of-two cases assert from_man_exp(72057594037927935, -56, 53, round_up) == (0, 1, 0, 1) assert from_man_exp(73786976294838205979, -65, 53, round_nearest) == (0, 1, 1, 1) assert from_man_exp(31, 0, 4, round_up) == (0, 1, 5, 1) assert from_man_exp(-31, 0, 4, round_floor) == (1, 1, 5, 1) assert from_man_exp(255, 0, 7, round_up) == (0, 1, 8, 1) assert from_man_exp(-255, 0, 7, round_floor) == (1, 1, 8, 1) def test_rounding_issue_200(): a = from_man_exp(9867,-100) b = from_man_exp(9867,-200) c = from_man_exp(-1,0) z = (1, 1023, -10, 10) assert mpf_add(a, c, 10, 'd') == z assert mpf_add(b, c, 10, 'd') == z assert mpf_add(c, a, 10, 'd') == z assert mpf_add(c, b, 10, 'd') == z def test_perturb(): a = fone b = from_float(0.99999999999999989) c = from_float(1.0000000000000002) assert mpf_perturb(a, 0, 53, round_nearest) == a assert mpf_perturb(a, 1, 53, round_nearest) == a assert mpf_perturb(a, 0, 53, round_up) == c assert mpf_perturb(a, 0, 53, round_ceiling) == c assert mpf_perturb(a, 0, 53, round_down) == a assert mpf_perturb(a, 0, 53, round_floor) == a assert mpf_perturb(a, 1, 53, round_up) == a assert mpf_perturb(a, 1, 53, round_ceiling) == a assert mpf_perturb(a, 1, 53, round_down) == b assert mpf_perturb(a, 1, 53, round_floor) == b a = mpf_neg(a) b = mpf_neg(b) c = mpf_neg(c) assert mpf_perturb(a, 0, 53, round_nearest) == a assert mpf_perturb(a, 1, 53, round_nearest) == a assert mpf_perturb(a, 0, 53, round_up) == a assert mpf_perturb(a, 0, 53, round_floor) == a assert mpf_perturb(a, 0, 53, round_down) == b assert mpf_perturb(a, 0, 53, round_ceiling) == b assert mpf_perturb(a, 1, 53, round_up) == c assert mpf_perturb(a, 1, 53, round_floor) == c assert mpf_perturb(a, 1, 53, round_down) == a assert mpf_perturb(a, 1, 53, round_ceiling) == a def test_add_exact(): ff = from_float assert mpf_add(ff(3.0), ff(2.5)) == ff(5.5) assert mpf_add(ff(3.0), ff(-2.5)) == ff(0.5) assert mpf_add(ff(-3.0), ff(2.5)) == ff(-0.5) assert mpf_add(ff(-3.0), ff(-2.5)) == ff(-5.5) assert mpf_sub(mpf_add(fone, ff(1e-100)), fone) == ff(1e-100) assert mpf_sub(mpf_add(ff(1e-100), fone), fone) == ff(1e-100) assert mpf_sub(mpf_add(fone, ff(-1e-100)), fone) == ff(-1e-100) assert mpf_sub(mpf_add(ff(-1e-100), fone), fone) == ff(-1e-100) assert mpf_add(fone, fzero) == fone assert mpf_add(fzero, fone) == fone assert mpf_add(fzero, fzero) == fzero def test_long_exponent_shifts(): mp.dps = 15 # Check for possible bugs due to exponent arithmetic overflow # in a C implementation x = mpf(1) for p in [32, 64]: a = ldexp(1,2**(p-1)) b = ldexp(1,2**p) c = ldexp(1,2**(p+1)) d = ldexp(1,-2**(p-1)) e = ldexp(1,-2**p) f = ldexp(1,-2**(p+1)) assert (x+a) == a assert (x+b) == b assert (x+c) == c assert (x+d) == x assert (x+e) == x assert (x+f) == x assert (a+x) == a assert (b+x) == b assert (c+x) == c assert (d+x) == x assert (e+x) == x assert (f+x) == x assert (x-a) == -a assert (x-b) == -b assert (x-c) == -c assert (x-d) == x assert (x-e) == x assert (x-f) == x assert (a-x) == a assert (b-x) == b assert (c-x) == c assert (d-x) == -x assert (e-x) == -x assert (f-x) == -x def test_float_rounding(): mp.prec = 64 for x in [mpf(1), mpf(1)+eps, mpf(1)-eps, -mpf(1)+eps, -mpf(1)-eps]: fa = float(x) fb = float(fadd(x,0,prec=53,rounding='n')) assert fa == fb z = mpc(x,x) ca = complex(z) cb = complex(fadd(z,0,prec=53,rounding='n')) assert ca == cb for rnd in ['n', 'd', 'u', 'f', 'c']: fa = to_float(x._mpf_, rnd=rnd) fb = to_float(fadd(x,0,prec=53,rounding=rnd)._mpf_, rnd=rnd) assert fa == fb mp.prec = 53
7,686
39.671958
95
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_division.py
from mpmath.libmp import * from mpmath import mpf, mp from random import randint, choice, seed all_modes = [round_floor, round_ceiling, round_down, round_up, round_nearest] fb = from_bstr fi = from_int ff = from_float def test_div_1_3(): a = fi(1) b = fi(3) c = fi(-1) # floor rounds down, ceiling rounds up assert mpf_div(a, b, 7, round_floor) == fb('0.01010101') assert mpf_div(a, b, 7, round_ceiling) == fb('0.01010110') assert mpf_div(a, b, 7, round_down) == fb('0.01010101') assert mpf_div(a, b, 7, round_up) == fb('0.01010110') assert mpf_div(a, b, 7, round_nearest) == fb('0.01010101') # floor rounds up, ceiling rounds down assert mpf_div(c, b, 7, round_floor) == fb('-0.01010110') assert mpf_div(c, b, 7, round_ceiling) == fb('-0.01010101') assert mpf_div(c, b, 7, round_down) == fb('-0.01010101') assert mpf_div(c, b, 7, round_up) == fb('-0.01010110') assert mpf_div(c, b, 7, round_nearest) == fb('-0.01010101') def test_mpf_divi_1_3(): a = 1 b = fi(3) c = -1 assert mpf_rdiv_int(a, b, 7, round_floor) == fb('0.01010101') assert mpf_rdiv_int(a, b, 7, round_ceiling) == fb('0.01010110') assert mpf_rdiv_int(a, b, 7, round_down) == fb('0.01010101') assert mpf_rdiv_int(a, b, 7, round_up) == fb('0.01010110') assert mpf_rdiv_int(a, b, 7, round_nearest) == fb('0.01010101') assert mpf_rdiv_int(c, b, 7, round_floor) == fb('-0.01010110') assert mpf_rdiv_int(c, b, 7, round_ceiling) == fb('-0.01010101') assert mpf_rdiv_int(c, b, 7, round_down) == fb('-0.01010101') assert mpf_rdiv_int(c, b, 7, round_up) == fb('-0.01010110') assert mpf_rdiv_int(c, b, 7, round_nearest) == fb('-0.01010101') def test_div_300(): q = fi(1000000) a = fi(300499999) # a/q is a little less than a half-integer b = fi(300500000) # b/q exactly a half-integer c = fi(300500001) # c/q is a little more than a half-integer # Check nearest integer rounding (prec=9 as 2**8 < 300 < 2**9) assert mpf_div(a, q, 9, round_down) == fi(300) assert mpf_div(b, q, 9, round_down) == fi(300) assert mpf_div(c, q, 9, round_down) == fi(300) assert mpf_div(a, q, 9, round_up) == fi(301) assert mpf_div(b, q, 9, round_up) == fi(301) assert mpf_div(c, q, 9, round_up) == fi(301) # Nearest even integer is down assert mpf_div(a, q, 9, round_nearest) == fi(300) assert mpf_div(b, q, 9, round_nearest) == fi(300) assert mpf_div(c, q, 9, round_nearest) == fi(301) # Nearest even integer is up a = fi(301499999) b = fi(301500000) c = fi(301500001) assert mpf_div(a, q, 9, round_nearest) == fi(301) assert mpf_div(b, q, 9, round_nearest) == fi(302) assert mpf_div(c, q, 9, round_nearest) == fi(302) def test_tight_integer_division(): # Test that integer division at tightest possible precision is exact N = 100 seed(1) for i in range(N): a = choice([1, -1]) * randint(1, 1<<randint(10, 100)) b = choice([1, -1]) * randint(1, 1<<randint(10, 100)) p = a * b width = bitcount(abs(b)) - trailing(b) a = fi(a); b = fi(b); p = fi(p) for mode in all_modes: assert mpf_div(p, a, width, mode) == b def test_epsilon_rounding(): # Verify that mpf_div uses infinite precision; this result will # appear to be exactly 0.101 to a near-sighted algorithm a = fb('0.101' + ('0'*200) + '1') b = fb('1.10101') c = mpf_mul(a, b, 250, round_floor) # exact assert mpf_div(c, b, bitcount(a[1]), round_floor) == a # exact assert mpf_div(c, b, 2, round_down) == fb('0.10') assert mpf_div(c, b, 3, round_down) == fb('0.101') assert mpf_div(c, b, 2, round_up) == fb('0.11') assert mpf_div(c, b, 3, round_up) == fb('0.110') assert mpf_div(c, b, 2, round_floor) == fb('0.10') assert mpf_div(c, b, 3, round_floor) == fb('0.101') assert mpf_div(c, b, 2, round_ceiling) == fb('0.11') assert mpf_div(c, b, 3, round_ceiling) == fb('0.110') # The same for negative numbers a = fb('-0.101' + ('0'*200) + '1') b = fb('1.10101') c = mpf_mul(a, b, 250, round_floor) assert mpf_div(c, b, bitcount(a[1]), round_floor) == a assert mpf_div(c, b, 2, round_down) == fb('-0.10') assert mpf_div(c, b, 3, round_up) == fb('-0.110') # Floor goes up, ceiling goes down assert mpf_div(c, b, 2, round_floor) == fb('-0.11') assert mpf_div(c, b, 3, round_floor) == fb('-0.110') assert mpf_div(c, b, 2, round_ceiling) == fb('-0.10') assert mpf_div(c, b, 3, round_ceiling) == fb('-0.101') def test_mod(): mp.dps = 15 assert mpf(234) % 1 == 0 assert mpf(-3) % 256 == 253 assert mpf(0.25) % 23490.5 == 0.25 assert mpf(0.25) % -23490.5 == -23490.25 assert mpf(-0.25) % 23490.5 == 23490.25 assert mpf(-0.25) % -23490.5 == -0.25 # Check that these cases are handled efficiently assert mpf('1e10000000000') % 1 == 0 assert mpf('1.23e-1000000000') % 1 == mpf('1.23e-1000000000') # test __rmod__ assert 3 % mpf('1.75') == 1.25 def test_div_negative_rnd_bug(): mp.dps = 15 assert (-3) / mpf('0.1531879017645047') == mpf('-19.583791966887116') assert mpf('-2.6342475750861301') / mpf('0.35126216427941814') == mpf('-7.4993775104985909')
5,340
36.090278
96
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/extratest_zeta.py
from mpmath import zetazero from timeit import default_timer as clock def test_zetazero(): cases = [\ (399999999, 156762524.6750591511), (241389216, 97490234.2276711795), (526196239, 202950727.691229534), (542964976, 209039046.578535272), (1048449112, 388858885.231056486), (1048449113, 388858885.384337406), (1048449114, 388858886.002285122), (1048449115, 388858886.00239369), (1048449116, 388858886.690745053) ] for n, v in cases: print(n, v) t1 = clock() ok = zetazero(n).ae(complex(0.5,v)) t2 = clock() print("ok =", ok, ("(time = %s)" % round(t2-t1,3))) print("Now computing two huge zeros (this may take hours)") print("Computing zetazero(8637740722917)") ok = zetazero(8637740722917).ae(complex(0.5,2124447368584.39296466152)) print("ok =", ok) ok = zetazero(8637740722918).ae(complex(0.5,2124447368584.39298170604)) print("ok =", ok) if __name__ == "__main__": try: import psyco psyco.full() except ImportError: pass test_zetazero()
1,091
29.333333
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_power.py
from mpmath import * from mpmath.libmp import * import random def test_fractional_pow(): mp.dps = 15 assert mpf(16) ** 2.5 == 1024 assert mpf(64) ** 0.5 == 8 assert mpf(64) ** -0.5 == 0.125 assert mpf(16) ** -2.5 == 0.0009765625 assert (mpf(10) ** 0.5).ae(3.1622776601683791) assert (mpf(10) ** 2.5).ae(316.2277660168379) assert (mpf(10) ** -0.5).ae(0.31622776601683794) assert (mpf(10) ** -2.5).ae(0.0031622776601683794) assert (mpf(10) ** 0.3).ae(1.9952623149688795) assert (mpf(10) ** -0.3).ae(0.50118723362727224) def test_pow_integer_direction(): """ Test that inexact integer powers are rounded in the right direction. """ random.seed(1234) for prec in [10, 53, 200]: for i in range(50): a = random.randint(1<<(prec-1), 1<<prec) b = random.randint(2, 100) ab = a**b # note: could actually be exact, but that's very unlikely! assert to_int(mpf_pow(from_int(a), from_int(b), prec, round_down)) < ab assert to_int(mpf_pow(from_int(a), from_int(b), prec, round_up)) > ab def test_pow_epsilon_rounding(): """ Stress test directed rounding for powers with integer exponents. Basically, we look at the following cases: >>> 1.0001 ** -5 # doctest: +SKIP 0.99950014996500702 >>> 0.9999 ** -5 # doctest: +SKIP 1.000500150035007 >>> (-1.0001) ** -5 # doctest: +SKIP -0.99950014996500702 >>> (-0.9999) ** -5 # doctest: +SKIP -1.000500150035007 >>> 1.0001 ** -6 # doctest: +SKIP 0.99940020994401269 >>> 0.9999 ** -6 # doctest: +SKIP 1.0006002100560125 >>> (-1.0001) ** -6 # doctest: +SKIP 0.99940020994401269 >>> (-0.9999) ** -6 # doctest: +SKIP 1.0006002100560125 etc. We run the tests with values a very small epsilon away from 1: small enough that the result is indistinguishable from 1 when rounded to nearest at the output precision. We check that the result is not erroneously rounded to 1 in cases where the rounding should be done strictly away from 1. """ def powr(x, n, r): return make_mpf(mpf_pow_int(x._mpf_, n, mp.prec, r)) for (inprec, outprec) in [(100, 20), (5000, 3000)]: mp.prec = inprec pos10001 = mpf(1) + mpf(2)**(-inprec+5) pos09999 = mpf(1) - mpf(2)**(-inprec+5) neg10001 = -pos10001 neg09999 = -pos09999 mp.prec = outprec r = round_up assert powr(pos10001, 5, r) > 1 assert powr(pos09999, 5, r) == 1 assert powr(neg10001, 5, r) < -1 assert powr(neg09999, 5, r) == -1 assert powr(pos10001, 6, r) > 1 assert powr(pos09999, 6, r) == 1 assert powr(neg10001, 6, r) > 1 assert powr(neg09999, 6, r) == 1 assert powr(pos10001, -5, r) == 1 assert powr(pos09999, -5, r) > 1 assert powr(neg10001, -5, r) == -1 assert powr(neg09999, -5, r) < -1 assert powr(pos10001, -6, r) == 1 assert powr(pos09999, -6, r) > 1 assert powr(neg10001, -6, r) == 1 assert powr(neg09999, -6, r) > 1 r = round_down assert powr(pos10001, 5, r) == 1 assert powr(pos09999, 5, r) < 1 assert powr(neg10001, 5, r) == -1 assert powr(neg09999, 5, r) > -1 assert powr(pos10001, 6, r) == 1 assert powr(pos09999, 6, r) < 1 assert powr(neg10001, 6, r) == 1 assert powr(neg09999, 6, r) < 1 assert powr(pos10001, -5, r) < 1 assert powr(pos09999, -5, r) == 1 assert powr(neg10001, -5, r) > -1 assert powr(neg09999, -5, r) == -1 assert powr(pos10001, -6, r) < 1 assert powr(pos09999, -6, r) == 1 assert powr(neg10001, -6, r) < 1 assert powr(neg09999, -6, r) == 1 r = round_ceiling assert powr(pos10001, 5, r) > 1 assert powr(pos09999, 5, r) == 1 assert powr(neg10001, 5, r) == -1 assert powr(neg09999, 5, r) > -1 assert powr(pos10001, 6, r) > 1 assert powr(pos09999, 6, r) == 1 assert powr(neg10001, 6, r) > 1 assert powr(neg09999, 6, r) == 1 assert powr(pos10001, -5, r) == 1 assert powr(pos09999, -5, r) > 1 assert powr(neg10001, -5, r) > -1 assert powr(neg09999, -5, r) == -1 assert powr(pos10001, -6, r) == 1 assert powr(pos09999, -6, r) > 1 assert powr(neg10001, -6, r) == 1 assert powr(neg09999, -6, r) > 1 r = round_floor assert powr(pos10001, 5, r) == 1 assert powr(pos09999, 5, r) < 1 assert powr(neg10001, 5, r) < -1 assert powr(neg09999, 5, r) == -1 assert powr(pos10001, 6, r) == 1 assert powr(pos09999, 6, r) < 1 assert powr(neg10001, 6, r) == 1 assert powr(neg09999, 6, r) < 1 assert powr(pos10001, -5, r) < 1 assert powr(pos09999, -5, r) == 1 assert powr(neg10001, -5, r) == -1 assert powr(neg09999, -5, r) < -1 assert powr(pos10001, -6, r) < 1 assert powr(pos09999, -6, r) == 1 assert powr(neg10001, -6, r) < 1 assert powr(neg09999, -6, r) == 1 mp.dps = 15
5,227
32.299363
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_functions2.py
import math from mpmath import * def test_bessel(): mp.dps = 15 assert j0(1).ae(0.765197686557966551) assert j0(pi).ae(-0.304242177644093864) assert j0(1000).ae(0.0247866861524201746) assert j0(-25).ae(0.0962667832759581162) assert j1(1).ae(0.440050585744933516) assert j1(pi).ae(0.284615343179752757) assert j1(1000).ae(0.00472831190708952392) assert j1(-25).ae(0.125350249580289905) assert besselj(5,1).ae(0.000249757730211234431) assert besselj(5+0j,1).ae(0.000249757730211234431) assert besselj(5,pi).ae(0.0521411843671184747) assert besselj(5,1000).ae(0.00502540694523318607) assert besselj(5,-25).ae(0.0660079953984229934) assert besselj(-3,2).ae(-0.128943249474402051) assert besselj(-4,2).ae(0.0339957198075684341) assert besselj(3,3+2j).ae(0.424718794929639595942 + 0.625665327745785804812j) assert besselj(0.25,4).ae(-0.374760630804249715) assert besselj(1+2j,3+4j).ae(0.319247428741872131 - 0.669557748880365678j) assert (besselj(3, 10**10) * 10**5).ae(0.76765081748139204023) assert bessely(-0.5, 0) == 0 assert bessely(0.5, 0) == -inf assert bessely(1.5, 0) == -inf assert bessely(0,0) == -inf assert bessely(-0.4, 0) == -inf assert bessely(-0.6, 0) == inf assert bessely(-1, 0) == inf assert bessely(-1.4, 0) == inf assert bessely(-1.6, 0) == -inf assert bessely(-1, 0) == inf assert bessely(-2, 0) == -inf assert bessely(-3, 0) == inf assert bessely(0.5, 0) == -inf assert bessely(1, 0) == -inf assert bessely(1.5, 0) == -inf assert bessely(2, 0) == -inf assert bessely(2.5, 0) == -inf assert bessely(3, 0) == -inf assert bessely(0,0.5).ae(-0.44451873350670655715) assert bessely(1,0.5).ae(-1.4714723926702430692) assert bessely(-1,0.5).ae(1.4714723926702430692) assert bessely(3.5,0.5).ae(-138.86400867242488443) assert bessely(0,3+4j).ae(4.6047596915010138655-8.8110771408232264208j) assert bessely(0,j).ae(-0.26803248203398854876+1.26606587775200833560j) assert (bessely(3, 10**10) * 10**5).ae(0.21755917537013204058) assert besseli(0,0) == 1 assert besseli(1,0) == 0 assert besseli(2,0) == 0 assert besseli(-1,0) == 0 assert besseli(-2,0) == 0 assert besseli(0,0.5).ae(1.0634833707413235193) assert besseli(1,0.5).ae(0.25789430539089631636) assert besseli(-1,0.5).ae(0.25789430539089631636) assert besseli(3.5,0.5).ae(0.00068103597085793815863) assert besseli(0,3+4j).ae(-3.3924877882755196097-1.3239458916287264815j) assert besseli(0,j).ae(besselj(0,1)) assert (besseli(3, 10**10) * mpf(10)**(-4342944813)).ae(4.2996028505491271875) assert besselk(0,0) == inf assert besselk(1,0) == inf assert besselk(2,0) == inf assert besselk(-1,0) == inf assert besselk(-2,0) == inf assert besselk(0,0.5).ae(0.92441907122766586178) assert besselk(1,0.5).ae(1.6564411200033008937) assert besselk(-1,0.5).ae(1.6564411200033008937) assert besselk(3.5,0.5).ae(207.48418747548460607) assert besselk(0,3+4j).ae(-0.007239051213570155013+0.026510418350267677215j) assert besselk(0,j).ae(-0.13863371520405399968-1.20196971531720649914j) assert (besselk(3, 10**10) * mpf(10)**4342944824).ae(1.1628981033356187851) # test for issue 331, bug reported by Michael Hartmann for n in range(10,100,10): mp.dps = n assert besseli(91.5,24.7708).ae("4.00830632138673963619656140653537080438462342928377020695738635559218797348548092636896796324190271316137982810144874264e-41") def test_bessel_zeros(): mp.dps = 15 assert besseljzero(0,1).ae(2.40482555769577276869) assert besseljzero(2,1).ae(5.1356223018406825563) assert besseljzero(1,50).ae(157.86265540193029781) assert besseljzero(10,1).ae(14.475500686554541220) assert besseljzero(0.5,3).ae(9.4247779607693797153) assert besseljzero(2,1,1).ae(3.0542369282271403228) assert besselyzero(0,1).ae(0.89357696627916752158) assert besselyzero(2,1).ae(3.3842417671495934727) assert besselyzero(1,50).ae(156.29183520147840108) assert besselyzero(10,1).ae(12.128927704415439387) assert besselyzero(0.5,3).ae(7.8539816339744830962) assert besselyzero(2,1,1).ae(5.0025829314460639452) def test_hankel(): mp.dps = 15 assert hankel1(0,0.5).ae(0.93846980724081290423-0.44451873350670655715j) assert hankel1(1,0.5).ae(0.2422684576748738864-1.4714723926702430692j) assert hankel1(-1,0.5).ae(-0.2422684576748738864+1.4714723926702430692j) assert hankel1(1.5,0.5).ae(0.0917016996256513026-2.5214655504213378514j) assert hankel1(1.5,3+4j).ae(0.0066806866476728165382-0.0036684231610839127106j) assert hankel2(0,0.5).ae(0.93846980724081290423+0.44451873350670655715j) assert hankel2(1,0.5).ae(0.2422684576748738864+1.4714723926702430692j) assert hankel2(-1,0.5).ae(-0.2422684576748738864-1.4714723926702430692j) assert hankel2(1.5,0.5).ae(0.0917016996256513026+2.5214655504213378514j) assert hankel2(1.5,3+4j).ae(14.783528526098567526-7.397390270853446512j) def test_struve(): mp.dps = 15 assert struveh(2,3).ae(0.74238666967748318564) assert struveh(-2.5,3).ae(0.41271003220971599344) assert struvel(2,3).ae(1.7476573277362782744) assert struvel(-2.5,3).ae(1.5153394466819651377) def test_whittaker(): mp.dps = 15 assert whitm(2,3,4).ae(49.753745589025246591) assert whitw(2,3,4).ae(14.111656223052932215) def test_kelvin(): mp.dps = 15 assert ber(2,3).ae(0.80836846563726819091) assert ber(3,4).ae(-0.28262680167242600233) assert ber(-3,2).ae(-0.085611448496796363669) assert bei(2,3).ae(-0.89102236377977331571) assert bei(-3,2).ae(-0.14420994155731828415) assert ker(2,3).ae(0.12839126695733458928) assert ker(-3,2).ae(-0.29802153400559142783) assert ker(0.5,3).ae(-0.085662378535217097524) assert kei(2,3).ae(0.036804426134164634000) assert kei(-3,2).ae(0.88682069845786731114) assert kei(0.5,3).ae(0.013633041571314302948) def test_hyper_misc(): mp.dps = 15 assert hyp0f1(1,0) == 1 assert hyp1f1(1,2,0) == 1 assert hyp1f2(1,2,3,0) == 1 assert hyp2f1(1,2,3,0) == 1 assert hyp2f2(1,2,3,4,0) == 1 assert hyp2f3(1,2,3,4,5,0) == 1 # Degenerate case: 0F0 assert hyper([],[],0) == 1 assert hyper([],[],-2).ae(exp(-2)) # Degenerate case: 1F0 assert hyper([2],[],1.5) == 4 # assert hyp2f1((1,3),(2,3),(5,6),mpf(27)/32).ae(1.6) assert hyp2f1((1,4),(1,2),(3,4),mpf(80)/81).ae(1.8) assert hyp2f1((2,3),(1,1),(3,2),(2+j)/3).ae(1.327531603558679093+0.439585080092769253j) mp.dps = 25 v = mpc('1.2282306665029814734863026', '-0.1225033830118305184672133') assert hyper([(3,4),2+j,1],[1,5,j/3],mpf(1)/5+j/8).ae(v) mp.dps = 15 def test_elliptic_integrals(): mp.dps = 15 assert ellipk(0).ae(pi/2) assert ellipk(0.5).ae(gamma(0.25)**2/(4*sqrt(pi))) assert ellipk(1) == inf assert ellipk(1+0j) == inf assert ellipk(-1).ae('1.3110287771460599052') assert ellipk(-2).ae('1.1714200841467698589') assert isinstance(ellipk(-2), mpf) assert isinstance(ellipe(-2), mpf) assert ellipk(-50).ae('0.47103424540873331679') mp.dps = 30 n1 = +fraction(99999,100000) n2 = +fraction(100001,100000) mp.dps = 15 assert ellipk(n1).ae('7.1427724505817781901') assert ellipk(n2).ae(mpc('7.1427417367963090109', '-1.5707923998261688019')) assert ellipe(n1).ae('1.0000332138990829170') v = ellipe(n2) assert v.real.ae('0.999966786328145474069137') assert (v.imag*10**6).ae('7.853952181727432') assert ellipk(2).ae(mpc('1.3110287771460599052', '-1.3110287771460599052')) assert ellipk(50).ae(mpc('0.22326753950210985451', '-0.47434723226254522087')) assert ellipk(3+4j).ae(mpc('0.91119556380496500866', '0.63133428324134524388')) assert ellipk(3-4j).ae(mpc('0.91119556380496500866', '-0.63133428324134524388')) assert ellipk(-3+4j).ae(mpc('0.95357894880405122483', '0.23093044503746114444')) assert ellipk(-3-4j).ae(mpc('0.95357894880405122483', '-0.23093044503746114444')) assert isnan(ellipk(nan)) assert isnan(ellipe(nan)) assert ellipk(inf) == 0 assert isinstance(ellipk(inf), mpc) assert ellipk(-inf) == 0 assert ellipk(1+0j) == inf assert ellipe(0).ae(pi/2) assert ellipe(0.5).ae(pi**(mpf(3)/2)/gamma(0.25)**2 +gamma(0.25)**2/(8*sqrt(pi))) assert ellipe(1) == 1 assert ellipe(1+0j) == 1 assert ellipe(inf) == mpc(0,inf) assert ellipe(-inf) == inf assert ellipe(3+4j).ae(1.4995535209333469543-1.5778790079127582745j) assert ellipe(3-4j).ae(1.4995535209333469543+1.5778790079127582745j) assert ellipe(-3+4j).ae(2.5804237855343377803-0.8306096791000413778j) assert ellipe(-3-4j).ae(2.5804237855343377803+0.8306096791000413778j) assert ellipe(2).ae(0.59907011736779610372+0.59907011736779610372j) assert ellipe('1e-1000000000').ae(pi/2) assert ellipk('1e-1000000000').ae(pi/2) assert ellipe(-pi).ae(2.4535865983838923) mp.dps = 50 assert ellipk(1/pi).ae('1.724756270009501831744438120951614673874904182624739673') assert ellipe(1/pi).ae('1.437129808135123030101542922290970050337425479058225712') assert ellipk(-10*pi).ae('0.5519067523886233967683646782286965823151896970015484512') assert ellipe(-10*pi).ae('5.926192483740483797854383268707108012328213431657645509') v = ellipk(pi) assert v.real.ae('0.973089521698042334840454592642137667227167622330325225') assert v.imag.ae('-1.156151296372835303836814390793087600271609993858798016') v = ellipe(pi) assert v.real.ae('0.4632848917264710404078033487934663562998345622611263332') assert v.imag.ae('1.0637961621753130852473300451583414489944099504180510966') mp.dps = 15 def test_exp_integrals(): mp.dps = 15 x = +e z = e + sqrt(3)*j assert ei(x).ae(8.21168165538361560) assert li(x).ae(1.89511781635593676) assert si(x).ae(1.82104026914756705) assert ci(x).ae(0.213958001340379779) assert shi(x).ae(4.11520706247846193) assert chi(x).ae(4.09647459290515367) assert fresnels(x).ae(0.437189718149787643) assert fresnelc(x).ae(0.401777759590243012) assert airyai(x).ae(0.0108502401568586681) assert airybi(x).ae(8.98245748585468627) assert ei(z).ae(3.72597969491314951 + 7.34213212314224421j) assert li(z).ae(2.28662658112562502 + 1.50427225297269364j) assert si(z).ae(2.48122029237669054 + 0.12684703275254834j) assert ci(z).ae(0.169255590269456633 - 0.892020751420780353j) assert shi(z).ae(1.85810366559344468 + 3.66435842914920263j) assert chi(z).ae(1.86787602931970484 + 3.67777369399304159j) assert fresnels(z/3).ae(0.034534397197008182 + 0.754859844188218737j) assert fresnelc(z/3).ae(1.261581645990027372 + 0.417949198775061893j) assert airyai(z).ae(-0.0162552579839056062 - 0.0018045715700210556j) assert airybi(z).ae(-4.98856113282883371 + 2.08558537872180623j) assert li(0) == 0.0 assert li(1) == -inf assert li(inf) == inf assert isinstance(li(0.7), mpf) assert si(inf).ae(pi/2) assert si(-inf).ae(-pi/2) assert ci(inf) == 0 assert ci(0) == -inf assert isinstance(ei(-0.7), mpf) assert airyai(inf) == 0 assert airybi(inf) == inf assert airyai(-inf) == 0 assert airybi(-inf) == 0 assert fresnels(inf) == 0.5 assert fresnelc(inf) == 0.5 assert fresnels(-inf) == -0.5 assert fresnelc(-inf) == -0.5 assert shi(0) == 0 assert shi(inf) == inf assert shi(-inf) == -inf assert chi(0) == -inf assert chi(inf) == inf def test_ei(): mp.dps = 15 assert ei(0) == -inf assert ei(inf) == inf assert ei(-inf) == -0.0 assert ei(20+70j).ae(6.1041351911152984397e6 - 2.7324109310519928872e6j) # tests for the asymptotic expansion # values checked with Mathematica ExpIntegralEi mp.dps = 50 r = ei(20000) s = '3.8781962825045010930273870085501819470698476975019e+8681' assert str(r) == s r = ei(-200) s = '-6.8852261063076355977108174824557929738368086933303e-90' assert str(r) == s r =ei(20000 + 10*j) sre = '-3.255138234032069402493850638874410725961401274106e+8681' sim = '-2.1081929993474403520785942429469187647767369645423e+8681' assert str(r.real) == sre and str(r.imag) == sim mp.dps = 15 # More asymptotic expansions assert chi(-10**6+100j).ae('1.3077239389562548386e+434288 + 7.6808956999707408158e+434287j') assert shi(-10**6+100j).ae('-1.3077239389562548386e+434288 - 7.6808956999707408158e+434287j') mp.dps = 15 assert ei(10j).ae(-0.0454564330044553726+3.2291439210137706686j) assert ei(100j).ae(-0.0051488251426104921+3.1330217936839529126j) u = ei(fmul(10**20, j, exact=True)) assert u.real.ae(-6.4525128526578084421345e-21, abs_eps=0, rel_eps=8*eps) assert u.imag.ae(pi) assert ei(-10j).ae(-0.0454564330044553726-3.2291439210137706686j) assert ei(-100j).ae(-0.0051488251426104921-3.1330217936839529126j) u = ei(fmul(-10**20, j, exact=True)) assert u.real.ae(-6.4525128526578084421345e-21, abs_eps=0, rel_eps=8*eps) assert u.imag.ae(-pi) assert ei(10+10j).ae(-1576.1504265768517448+436.9192317011328140j) u = ei(-10+10j) assert u.real.ae(7.6698978415553488362543e-7, abs_eps=0, rel_eps=8*eps) assert u.imag.ae(3.141595611735621062025) def test_e1(): mp.dps = 15 assert e1(0) == inf assert e1(inf) == 0 assert e1(-inf) == mpc(-inf, -pi) assert e1(10j).ae(0.045456433004455372635 + 0.087551267423977430100j) assert e1(100j).ae(0.0051488251426104921444 - 0.0085708599058403258790j) assert e1(fmul(10**20, j, exact=True)).ae(6.4525128526578084421e-21 - 7.6397040444172830039e-21j, abs_eps=0, rel_eps=8*eps) assert e1(-10j).ae(0.045456433004455372635 - 0.087551267423977430100j) assert e1(-100j).ae(0.0051488251426104921444 + 0.0085708599058403258790j) assert e1(fmul(-10**20, j, exact=True)).ae(6.4525128526578084421e-21 + 7.6397040444172830039e-21j, abs_eps=0, rel_eps=8*eps) def test_expint(): mp.dps = 15 assert expint(0,0) == inf assert expint(0,1).ae(1/e) assert expint(0,1.5).ae(2/exp(1.5)/3) assert expint(1,1).ae(-ei(-1)) assert expint(2,0).ae(1) assert expint(3,0).ae(1/2.) assert expint(4,0).ae(1/3.) assert expint(-2, 0.5).ae(26/sqrt(e)) assert expint(-1,-1) == 0 assert expint(-2,-1).ae(-e) assert expint(5.5, 0).ae(2/9.) assert expint(2.00000001,0).ae(100000000./100000001) assert expint(2+3j,4-j).ae(0.0023461179581675065414+0.0020395540604713669262j) assert expint('1.01', '1e-1000').ae(99.9999999899412802) assert expint('1.000000000001', 3.5).ae(0.00697013985754701819446) assert expint(2,3).ae(3*ei(-3)+exp(-3)) assert (expint(10,20)*10**10).ae(0.694439055541231353) assert expint(3,inf) == 0 assert expint(3.2,inf) == 0 assert expint(3.2+2j,inf) == 0 assert expint(1,3j).ae(-0.11962978600800032763 + 0.27785620120457163717j) assert expint(1,3).ae(0.013048381094197037413) assert expint(1,-3).ae(-ei(3)-pi*j) #assert expint(3) == expint(1,3) assert expint(1,-20).ae(-25615652.66405658882 - 3.1415926535897932385j) assert expint(1000000,0).ae(1./999999) assert expint(0,2+3j).ae(-0.025019798357114678171 + 0.027980439405104419040j) assert expint(-1,2+3j).ae(-0.022411973626262070419 + 0.038058922011377716932j) assert expint(-1.5,0) == inf def test_trig_integrals(): mp.dps = 30 assert si(mpf(1)/1000000).ae('0.000000999999999999944444444444446111') assert ci(mpf(1)/1000000).ae('-13.2382948930629912435014366276') assert si(10**10).ae('1.5707963267075846569685111517747537') assert ci(10**10).ae('-4.87506025174822653785729773959e-11') assert si(10**100).ae(pi/2) assert (ci(10**100)*10**100).ae('-0.372376123661276688262086695553') assert si(-3) == -si(3) assert ci(-3).ae(ci(3) + pi*j) # Test complex structure mp.dps = 15 assert mp.ci(50).ae(-0.0056283863241163054402) assert mp.ci(50+2j).ae(-0.018378282946133067149+0.070352808023688336193j) assert mp.ci(20j).ae(1.28078263320282943611e7+1.5707963267949j) assert mp.ci(-2+20j).ae(-4.050116856873293505e6+1.207476188206989909e7j) assert mp.ci(-50+2j).ae(-0.0183782829461330671+3.0712398455661049023j) assert mp.ci(-50).ae(-0.0056283863241163054+3.1415926535897932385j) assert mp.ci(-50-2j).ae(-0.0183782829461330671-3.0712398455661049023j) assert mp.ci(-2-20j).ae(-4.050116856873293505e6-1.207476188206989909e7j) assert mp.ci(-20j).ae(1.28078263320282943611e7-1.5707963267949j) assert mp.ci(50-2j).ae(-0.018378282946133067149-0.070352808023688336193j) assert mp.si(50).ae(1.5516170724859358947) assert mp.si(50+2j).ae(1.497884414277228461-0.017515007378437448j) assert mp.si(20j).ae(1.2807826332028294459e7j) assert mp.si(-2+20j).ae(-1.20747603112735722103e7-4.050116856873293554e6j) assert mp.si(-50+2j).ae(-1.497884414277228461-0.017515007378437448j) assert mp.si(-50).ae(-1.5516170724859358947) assert mp.si(-50-2j).ae(-1.497884414277228461+0.017515007378437448j) assert mp.si(-2-20j).ae(-1.20747603112735722103e7+4.050116856873293554e6j) assert mp.si(-20j).ae(-1.2807826332028294459e7j) assert mp.si(50-2j).ae(1.497884414277228461+0.017515007378437448j) assert mp.chi(50j).ae(-0.0056283863241163054+1.5707963267948966192j) assert mp.chi(-2+50j).ae(-0.0183782829461330671+1.6411491348185849554j) assert mp.chi(-20).ae(1.28078263320282943611e7+3.1415926535898j) assert mp.chi(-20-2j).ae(-4.050116856873293505e6+1.20747571696809187053e7j) assert mp.chi(-2-50j).ae(-0.0183782829461330671-1.6411491348185849554j) assert mp.chi(-50j).ae(-0.0056283863241163054-1.5707963267948966192j) assert mp.chi(2-50j).ae(-0.0183782829461330671-1.500443518771208283j) assert mp.chi(20-2j).ae(-4.050116856873293505e6-1.20747603112735722951e7j) assert mp.chi(20).ae(1.2807826332028294361e7) assert mp.chi(2+50j).ae(-0.0183782829461330671+1.500443518771208283j) assert mp.shi(50j).ae(1.5516170724859358947j) assert mp.shi(-2+50j).ae(0.017515007378437448+1.497884414277228461j) assert mp.shi(-20).ae(-1.2807826332028294459e7) assert mp.shi(-20-2j).ae(4.050116856873293554e6-1.20747603112735722103e7j) assert mp.shi(-2-50j).ae(0.017515007378437448-1.497884414277228461j) assert mp.shi(-50j).ae(-1.5516170724859358947j) assert mp.shi(2-50j).ae(-0.017515007378437448-1.497884414277228461j) assert mp.shi(20-2j).ae(-4.050116856873293554e6-1.20747603112735722103e7j) assert mp.shi(20).ae(1.2807826332028294459e7) assert mp.shi(2+50j).ae(-0.017515007378437448+1.497884414277228461j) def ae(x,y,tol=1e-12): return abs(x-y) <= abs(y)*tol assert fp.ci(fp.inf) == 0 assert ae(fp.ci(fp.ninf), fp.pi*1j) assert ae(fp.si(fp.inf), fp.pi/2) assert ae(fp.si(fp.ninf), -fp.pi/2) assert fp.si(0) == 0 assert ae(fp.ci(50), -0.0056283863241163054402) assert ae(fp.ci(50+2j), -0.018378282946133067149+0.070352808023688336193j) assert ae(fp.ci(20j), 1.28078263320282943611e7+1.5707963267949j) assert ae(fp.ci(-2+20j), -4.050116856873293505e6+1.207476188206989909e7j) assert ae(fp.ci(-50+2j), -0.0183782829461330671+3.0712398455661049023j) assert ae(fp.ci(-50), -0.0056283863241163054+3.1415926535897932385j) assert ae(fp.ci(-50-2j), -0.0183782829461330671-3.0712398455661049023j) assert ae(fp.ci(-2-20j), -4.050116856873293505e6-1.207476188206989909e7j) assert ae(fp.ci(-20j), 1.28078263320282943611e7-1.5707963267949j) assert ae(fp.ci(50-2j), -0.018378282946133067149-0.070352808023688336193j) assert ae(fp.si(50), 1.5516170724859358947) assert ae(fp.si(50+2j), 1.497884414277228461-0.017515007378437448j) assert ae(fp.si(20j), 1.2807826332028294459e7j) assert ae(fp.si(-2+20j), -1.20747603112735722103e7-4.050116856873293554e6j) assert ae(fp.si(-50+2j), -1.497884414277228461-0.017515007378437448j) assert ae(fp.si(-50), -1.5516170724859358947) assert ae(fp.si(-50-2j), -1.497884414277228461+0.017515007378437448j) assert ae(fp.si(-2-20j), -1.20747603112735722103e7+4.050116856873293554e6j) assert ae(fp.si(-20j), -1.2807826332028294459e7j) assert ae(fp.si(50-2j), 1.497884414277228461+0.017515007378437448j) assert ae(fp.chi(50j), -0.0056283863241163054+1.5707963267948966192j) assert ae(fp.chi(-2+50j), -0.0183782829461330671+1.6411491348185849554j) assert ae(fp.chi(-20), 1.28078263320282943611e7+3.1415926535898j) assert ae(fp.chi(-20-2j), -4.050116856873293505e6+1.20747571696809187053e7j) assert ae(fp.chi(-2-50j), -0.0183782829461330671-1.6411491348185849554j) assert ae(fp.chi(-50j), -0.0056283863241163054-1.5707963267948966192j) assert ae(fp.chi(2-50j), -0.0183782829461330671-1.500443518771208283j) assert ae(fp.chi(20-2j), -4.050116856873293505e6-1.20747603112735722951e7j) assert ae(fp.chi(20), 1.2807826332028294361e7) assert ae(fp.chi(2+50j), -0.0183782829461330671+1.500443518771208283j) assert ae(fp.shi(50j), 1.5516170724859358947j) assert ae(fp.shi(-2+50j), 0.017515007378437448+1.497884414277228461j) assert ae(fp.shi(-20), -1.2807826332028294459e7) assert ae(fp.shi(-20-2j), 4.050116856873293554e6-1.20747603112735722103e7j) assert ae(fp.shi(-2-50j), 0.017515007378437448-1.497884414277228461j) assert ae(fp.shi(-50j), -1.5516170724859358947j) assert ae(fp.shi(2-50j), -0.017515007378437448-1.497884414277228461j) assert ae(fp.shi(20-2j), -4.050116856873293554e6-1.20747603112735722103e7j) assert ae(fp.shi(20), 1.2807826332028294459e7) assert ae(fp.shi(2+50j), -0.017515007378437448+1.497884414277228461j) def test_airy(): mp.dps = 15 assert (airyai(10)*10**10).ae(1.1047532552898687) assert (airybi(10)/10**9).ae(0.45564115354822515) assert (airyai(1000)*10**9158).ae(9.306933063179556004) assert (airybi(1000)/10**9154).ae(5.4077118391949465477) assert airyai(-1000).ae(0.055971895773019918842) assert airybi(-1000).ae(-0.083264574117080633012) assert (airyai(100+100j)*10**188).ae(2.9099582462207032076 + 2.353013591706178756j) assert (airybi(100+100j)/10**185).ae(1.7086751714463652039 - 3.1416590020830804578j) def test_hyper_0f1(): mp.dps = 15 v = 8.63911136507950465 assert hyper([],[(1,3)],1.5).ae(v) assert hyper([],[1/3.],1.5).ae(v) assert hyp0f1(1/3.,1.5).ae(v) assert hyp0f1((1,3),1.5).ae(v) # Asymptotic expansion assert hyp0f1(3,1e9).ae('4.9679055380347771271e+27455') assert hyp0f1(3,1e9j).ae('-2.1222788784457702157e+19410 + 5.0840597555401854116e+19410j') def test_hyper_1f1(): mp.dps = 15 v = 1.2917526488617656673 assert hyper([(1,2)],[(3,2)],0.7).ae(v) assert hyper([(1,2)],[(3,2)],0.7+0j).ae(v) assert hyper([0.5],[(3,2)],0.7).ae(v) assert hyper([0.5],[1.5],0.7).ae(v) assert hyper([0.5],[(3,2)],0.7+0j).ae(v) assert hyper([0.5],[1.5],0.7+0j).ae(v) assert hyper([(1,2)],[1.5+0j],0.7).ae(v) assert hyper([0.5+0j],[1.5],0.7).ae(v) assert hyper([0.5+0j],[1.5+0j],0.7+0j).ae(v) assert hyp1f1(0.5,1.5,0.7).ae(v) assert hyp1f1((1,2),1.5,0.7).ae(v) # Asymptotic expansion assert hyp1f1(2,3,1e10).ae('2.1555012157015796988e+4342944809') assert (hyp1f1(2,3,1e10j)*10**10).ae(-0.97501205020039745852 - 1.7462392454512132074j) # Shouldn't use asymptotic expansion assert hyp1f1(-2, 1, 10000).ae(49980001) # Bug assert hyp1f1(1j,fraction(1,3),0.415-69.739j).ae(25.857588206024346592 + 15.738060264515292063j) def test_hyper_2f1(): mp.dps = 15 v = 1.0652207633823291032 assert hyper([(1,2), (3,4)], [2], 0.3).ae(v) assert hyper([(1,2), 0.75], [2], 0.3).ae(v) assert hyper([0.5, 0.75], [2.0], 0.3).ae(v) assert hyper([0.5, 0.75], [2.0], 0.3+0j).ae(v) assert hyper([0.5+0j, (3,4)], [2.0], 0.3+0j).ae(v) assert hyper([0.5+0j, (3,4)], [2.0], 0.3).ae(v) assert hyper([0.5, (3,4)], [2.0+0j], 0.3).ae(v) assert hyper([0.5+0j, 0.75+0j], [2.0+0j], 0.3+0j).ae(v) v = 1.09234681096223231717 + 0.18104859169479360380j assert hyper([(1,2),0.75+j], [2], 0.5).ae(v) assert hyper([0.5,0.75+j], [2.0], 0.5).ae(v) assert hyper([0.5,0.75+j], [2.0], 0.5+0j).ae(v) assert hyper([0.5,0.75+j], [2.0+0j], 0.5+0j).ae(v) v = 0.9625 - 0.125j assert hyper([(3,2),-1],[4], 0.1+j/3).ae(v) assert hyper([1.5,-1.0],[4], 0.1+j/3).ae(v) assert hyper([1.5,-1.0],[4+0j], 0.1+j/3).ae(v) assert hyper([1.5+0j,-1.0+0j],[4+0j], 0.1+j/3).ae(v) v = 1.02111069501693445001 - 0.50402252613466859521j assert hyper([(2,10),(3,10)],[(4,10)],1.5).ae(v) assert hyper([0.2,(3,10)],[0.4+0j],1.5).ae(v) assert hyper([0.2,(3,10)],[0.4+0j],1.5+0j).ae(v) v = 0.76922501362865848528 + 0.32640579593235886194j assert hyper([(2,10),(3,10)],[(4,10)],4+2j).ae(v) assert hyper([0.2,(3,10)],[0.4+0j],4+2j).ae(v) assert hyper([0.2,(3,10)],[(4,10)],4+2j).ae(v) def test_hyper_2f1_hard(): mp.dps = 15 # Singular cases assert hyp2f1(2,-1,-1,3).ae(7) assert hyp2f1(2,-1,-1,3,eliminate_all=True).ae(0.25) assert hyp2f1(2,-2,-2,3).ae(34) assert hyp2f1(2,-2,-2,3,eliminate_all=True).ae(0.25) assert hyp2f1(2,-2,-3,3) == 14 assert hyp2f1(2,-3,-2,3) == inf assert hyp2f1(2,-1.5,-1.5,3) == 0.25 assert hyp2f1(1,2,3,0) == 1 assert hyp2f1(0,1,0,0) == 1 assert hyp2f1(0,0,0,0) == 1 assert isnan(hyp2f1(1,1,0,0)) assert hyp2f1(2,-1,-5, 0.25+0.25j).ae(1.1+0.1j) assert hyp2f1(2,-5,-5, 0.25+0.25j, eliminate=False).ae(163./128 + 125./128*j) assert hyp2f1(0.7235, -1, -5, 0.3).ae(1.04341) assert hyp2f1(0.7235, -5, -5, 0.3, eliminate=False).ae(1.2939225017815903812) assert hyp2f1(-1,-2,4,1) == 1.5 assert hyp2f1(1,2,-3,1) == inf assert hyp2f1(-2,-2,1,1) == 6 assert hyp2f1(1,-2,-4,1).ae(5./3) assert hyp2f1(0,-6,-4,1) == 1 assert hyp2f1(0,-3,-4,1) == 1 assert hyp2f1(0,0,0,1) == 1 assert hyp2f1(1,0,0,1,eliminate=False) == 1 assert hyp2f1(1,1,0,1) == inf assert hyp2f1(1,-6,-4,1) == inf assert hyp2f1(-7.2,-0.5,-4.5,1) == 0 assert hyp2f1(-7.2,-1,-2,1).ae(-2.6) assert hyp2f1(1,-0.5,-4.5, 1) == inf assert hyp2f1(1,0.5,-4.5, 1) == -inf # Check evaluation on / close to unit circle z = exp(j*pi/3) w = (nthroot(2,3)+1)*exp(j*pi/12)/nthroot(3,4)**3 assert hyp2f1('1/2','1/6','1/3', z).ae(w) assert hyp2f1('1/2','1/6','1/3', z.conjugate()).ae(w.conjugate()) assert hyp2f1(0.25, (1,3), 2, '0.999').ae(1.06826449496030635) assert hyp2f1(0.25, (1,3), 2, '1.001').ae(1.06867299254830309446-0.00001446586793975874j) assert hyp2f1(0.25, (1,3), 2, -1).ae(0.96656584492524351673) assert hyp2f1(0.25, (1,3), 2, j).ae(0.99041766248982072266+0.03777135604180735522j) assert hyp2f1(2,3,5,'0.99').ae(27.699347904322690602) assert hyp2f1((3,2),-0.5,3,'0.99').ae(0.68403036843911661388) assert hyp2f1(2,3,5,1j).ae(0.37290667145974386127+0.59210004902748285917j) assert fsum([hyp2f1((7,10),(2,3),(-1,2), 0.95*exp(j*k)) for k in range(1,15)]).ae(52.851400204289452922+6.244285013912953225j) assert fsum([hyp2f1((7,10),(2,3),(-1,2), 1.05*exp(j*k)) for k in range(1,15)]).ae(54.506013786220655330-3.000118813413217097j) assert fsum([hyp2f1((7,10),(2,3),(-1,2), exp(j*k)) for k in range(1,15)]).ae(55.792077935955314887+1.731986485778500241j) assert hyp2f1(2,2.5,-3.25,0.999).ae(218373932801217082543180041.33) # Branches assert hyp2f1(1,1,2,1.01).ae(4.5595744415723676911-3.1104877758314784539j) assert hyp2f1(1,1,2,1.01+0.1j).ae(2.4149427480552782484+1.4148224796836938829j) assert hyp2f1(1,1,2,3+4j).ae(0.14576709331407297807+0.48379185417980360773j) assert hyp2f1(1,1,2,4).ae(-0.27465307216702742285 - 0.78539816339744830962j) assert hyp2f1(1,1,2,-4).ae(0.40235947810852509365) # Other: # Cancellation with a large parameter involved (bug reported on sage-devel) assert hyp2f1(112, (51,10), (-9,10), -0.99999).ae(-1.6241361047970862961e-24, abs_eps=0, rel_eps=eps*16) def test_hyper_3f2_etc(): assert hyper([1,2,3],[1.5,8],-1).ae(0.67108992351533333030) assert hyper([1,2,3,4],[5,6,7], -1).ae(0.90232988035425506008) assert hyper([1,2,3],[1.25,5], 1).ae(28.924181329701905701) assert hyper([1,2,3,4],[5,6,7],5).ae(1.5192307344006649499-1.1529845225075537461j) assert hyper([1,2,3,4,5],[6,7,8,9],-1).ae(0.96288759462882357253) assert hyper([1,2,3,4,5],[6,7,8,9],1).ae(1.0428697385885855841) assert hyper([1,2,3,4,5],[6,7,8,9],5).ae(1.33980653631074769423-0.07143405251029226699j) assert hyper([1,2.79,3.08,4.37],[5.2,6.1,7.3],5).ae(1.0996321464692607231-1.7748052293979985001j) assert hyper([1,1,1],[1,2],1) == inf assert hyper([1,1,1],[2,(101,100)],1).ae(100.01621213528313220) # slow -- covered by doctests #assert hyper([1,1,1],[2,3],0.9999).ae(1.2897972005319693905) def test_hyper_u(): mp.dps = 15 assert hyperu(2,-3,0).ae(0.05) assert hyperu(2,-3.5,0).ae(4./99) assert hyperu(2,0,0) == 0.5 assert hyperu(-5,1,0) == -120 assert hyperu(-5,2,0) == inf assert hyperu(-5,-2,0) == 0 assert hyperu(7,7,3).ae(0.00014681269365593503986) #exp(3)*gammainc(-6,3) assert hyperu(2,-3,4).ae(0.011836478100271995559) assert hyperu(3,4,5).ae(1./125) assert hyperu(2,3,0.0625) == 256 assert hyperu(-1,2,0.25+0.5j) == -1.75+0.5j assert hyperu(0.5,1.5,7.25).ae(2/sqrt(29)) assert hyperu(2,6,pi).ae(0.55804439825913399130) assert (hyperu((3,2),8,100+201j)*10**4).ae(-0.3797318333856738798 - 2.9974928453561707782j) assert (hyperu((5,2),(-1,2),-5000)*10**10).ae(-5.6681877926881664678j) # XXX: fails because of undetected cancellation in low level series code # Alternatively: could use asymptotic series here, if convergence test # tweaked back to recognize this one #assert (hyperu((5,2),(-1,2),-500)*10**7).ae(-1.82526906001593252847j) def test_hyper_2f0(): mp.dps = 15 assert hyper([1,2],[],3) == hyp2f0(1,2,3) assert hyp2f0(2,3,7).ae(0.0116108068639728714668 - 0.0073727413865865802130j) assert hyp2f0(2,3,0) == 1 assert hyp2f0(0,0,0) == 1 assert hyp2f0(-1,-1,1).ae(2) assert hyp2f0(-4,1,1.5).ae(62.5) assert hyp2f0(-4,1,50).ae(147029801) assert hyp2f0(-4,1,0.0001).ae(0.99960011997600240000) assert hyp2f0(0.5,0.25,0.001).ae(1.0001251174078538115) assert hyp2f0(0.5,0.25,3+4j).ae(0.85548875824755163518 + 0.21636041283392292973j) # Important: cancellation check assert hyp2f0((1,6),(5,6),-0.02371708245126284498).ae(0.996785723120804309) # Should be exact; polynomial case assert hyp2f0(-2,1,0.5+0.5j,zeroprec=200) == 0 assert hyp2f0(1,-2,0.5+0.5j,zeroprec=200) == 0 # There used to be a bug in thresholds that made one of the following hang for d in [15, 50, 80]: mp.dps = d assert hyp2f0(1.5, 0.5, 0.009).ae('1.006867007239309717945323585695344927904000945829843527398772456281301440034218290443367270629519483 + 1.238277162240704919639384945859073461954721356062919829456053965502443570466701567100438048602352623e-46j') def test_hyper_1f2(): mp.dps = 15 assert hyper([1],[2,3],4) == hyp1f2(1,2,3,4) a1,b1,b2 = (1,10),(2,3),1./16 assert hyp1f2(a1,b1,b2,10).ae(298.7482725554557568) assert hyp1f2(a1,b1,b2,100).ae(224128961.48602947604) assert hyp1f2(a1,b1,b2,1000).ae(1.1669528298622675109e+27) assert hyp1f2(a1,b1,b2,10000).ae(2.4780514622487212192e+86) assert hyp1f2(a1,b1,b2,100000).ae(1.3885391458871523997e+274) assert hyp1f2(a1,b1,b2,1000000).ae('9.8851796978960318255e+867') assert hyp1f2(a1,b1,b2,10**7).ae('1.1505659189516303646e+2746') assert hyp1f2(a1,b1,b2,10**8).ae('1.4672005404314334081e+8685') assert hyp1f2(a1,b1,b2,10**20).ae('3.6888217332150976493e+8685889636') assert hyp1f2(a1,b1,b2,10*j).ae(-16.163252524618572878 - 44.321567896480184312j) assert hyp1f2(a1,b1,b2,100*j).ae(61938.155294517848171 + 637349.45215942348739j) assert hyp1f2(a1,b1,b2,1000*j).ae(8455057657257695958.7 + 6261969266997571510.6j) assert hyp1f2(a1,b1,b2,10000*j).ae(-8.9771211184008593089e+60 + 4.6550528111731631456e+59j) assert hyp1f2(a1,b1,b2,100000*j).ae(2.6398091437239324225e+193 + 4.1658080666870618332e+193j) assert hyp1f2(a1,b1,b2,1000000*j).ae('3.5999042951925965458e+613 + 1.5026014707128947992e+613j') assert hyp1f2(a1,b1,b2,10**7*j).ae('-8.3208715051623234801e+1939 - 3.6752883490851869429e+1941j') assert hyp1f2(a1,b1,b2,10**8*j).ae('2.0724195707891484454e+6140 - 1.3276619482724266387e+6141j') assert hyp1f2(a1,b1,b2,10**20*j).ae('-1.1734497974795488504e+6141851462 + 1.1498106965385471542e+6141851462j') def test_hyper_2f3(): mp.dps = 15 assert hyper([1,2],[3,4,5],6) == hyp2f3(1,2,3,4,5,6) a1,a2,b1,b2,b3 = (1,10),(2,3),(3,10), 2, 1./16 # Check asymptotic expansion assert hyp2f3(a1,a2,b1,b2,b3,10).ae(128.98207160698659976) assert hyp2f3(a1,a2,b1,b2,b3,1000).ae(6.6309632883131273141e25) assert hyp2f3(a1,a2,b1,b2,b3,10000).ae(4.6863639362713340539e84) assert hyp2f3(a1,a2,b1,b2,b3,100000).ae(8.6632451236103084119e271) assert hyp2f3(a1,a2,b1,b2,b3,10**6).ae('2.0291718386574980641e865') assert hyp2f3(a1,a2,b1,b2,b3,10**7).ae('7.7639836665710030977e2742') assert hyp2f3(a1,a2,b1,b2,b3,10**8).ae('3.2537462584071268759e8681') assert hyp2f3(a1,a2,b1,b2,b3,10**20).ae('1.2966030542911614163e+8685889627') assert hyp2f3(a1,a2,b1,b2,b3,10*j).ae(-18.551602185587547854 - 13.348031097874113552j) assert hyp2f3(a1,a2,b1,b2,b3,100*j).ae(78634.359124504488695 + 74459.535945281973996j) assert hyp2f3(a1,a2,b1,b2,b3,1000*j).ae(597682550276527901.59 - 65136194809352613.078j) assert hyp2f3(a1,a2,b1,b2,b3,10000*j).ae(-1.1779696326238582496e+59 + 1.2297607505213133872e+59j) assert hyp2f3(a1,a2,b1,b2,b3,100000*j).ae(2.9844228969804380301e+191 + 7.5587163231490273296e+190j) assert hyp2f3(a1,a2,b1,b2,b3,1000000*j).ae('7.4859161049322370311e+610 - 2.8467477015940090189e+610j') assert hyp2f3(a1,a2,b1,b2,b3,10**7*j).ae('-1.7477645579418800826e+1938 - 1.7606522995808116405e+1938j') assert hyp2f3(a1,a2,b1,b2,b3,10**8*j).ae('-1.6932731942958401784e+6137 - 2.4521909113114629368e+6137j') assert hyp2f3(a1,a2,b1,b2,b3,10**20*j).ae('-2.0988815677627225449e+6141851451 + 5.7708223542739208681e+6141851452j') def test_hyper_2f2(): mp.dps = 15 assert hyper([1,2],[3,4],5) == hyp2f2(1,2,3,4,5) a1,a2,b1,b2 = (3,10),4,(1,2),1./16 assert hyp2f2(a1,a2,b1,b2,10).ae(448225936.3377556696) assert hyp2f2(a1,a2,b1,b2,10000).ae('1.2012553712966636711e+4358') assert hyp2f2(a1,a2,b1,b2,-20000).ae(-0.04182343755661214626) assert hyp2f2(a1,a2,b1,b2,10**20).ae('1.1148680024303263661e+43429448190325182840') def test_orthpoly(): mp.dps = 15 assert jacobi(-4,2,3,0.7).ae(22800./4913) assert jacobi(3,2,4,5.5) == 4133.125 assert jacobi(1.5,5/6.,4,0).ae(-1.0851951434075508417) assert jacobi(-2, 1, 2, 4).ae(-0.16) assert jacobi(2, -1, 2.5, 4).ae(34.59375) #assert jacobi(2, -1, 2, 4) == 28.5 assert legendre(5, 7) == 129367 assert legendre(0.5,0).ae(0.53935260118837935667) assert legendre(-1,-1) == 1 assert legendre(0,-1) == 1 assert legendre(0, 1) == 1 assert legendre(1, -1) == -1 assert legendre(7, 1) == 1 assert legendre(7, -1) == -1 assert legendre(8,1.5).ae(15457523./32768) assert legendre(j,-j).ae(2.4448182735671431011 + 0.6928881737669934843j) assert chebyu(5,1) == 6 assert chebyt(3,2) == 26 assert legendre(3.5,-1) == inf assert legendre(4.5,-1) == -inf assert legendre(3.5+1j,-1) == mpc(inf,inf) assert legendre(4.5+1j,-1) == mpc(-inf,-inf) assert laguerre(4, -2, 3).ae(-1.125) assert laguerre(3, 1+j, 0.5).ae(0.2291666666666666667 + 2.5416666666666666667j) def test_hermite(): mp.dps = 15 assert hermite(-2, 0).ae(0.5) assert hermite(-1, 0).ae(0.88622692545275801365) assert hermite(0, 0).ae(1) assert hermite(1, 0) == 0 assert hermite(2, 0).ae(-2) assert hermite(0, 2).ae(1) assert hermite(1, 2).ae(4) assert hermite(1, -2).ae(-4) assert hermite(2, -2).ae(14) assert hermite(0.5, 0).ae(0.69136733903629335053) assert hermite(9, 0) == 0 assert hermite(4,4).ae(3340) assert hermite(3,4).ae(464) assert hermite(-4,4).ae(0.00018623860287512396181) assert hermite(-3,4).ae(0.0016540169879668766270) assert hermite(9, 2.5j).ae(13638725j) assert hermite(9, -2.5j).ae(-13638725j) assert hermite(9, 100).ae(511078883759363024000) assert hermite(9, -100).ae(-511078883759363024000) assert hermite(9, 100j).ae(512922083920643024000j) assert hermite(9, -100j).ae(-512922083920643024000j) assert hermite(-9.5, 2.5j).ae(-2.9004951258126778174e-6 + 1.7601372934039951100e-6j) assert hermite(-9.5, -2.5j).ae(-2.9004951258126778174e-6 - 1.7601372934039951100e-6j) assert hermite(-9.5, 100).ae(1.3776300722767084162e-22, abs_eps=0, rel_eps=eps) assert hermite(-9.5, -100).ae('1.3106082028470671626e4355') assert hermite(-9.5, 100j).ae(-9.7900218581864768430e-23 - 9.7900218581864768430e-23j, abs_eps=0, rel_eps=eps) assert hermite(-9.5, -100j).ae(-9.7900218581864768430e-23 + 9.7900218581864768430e-23j, abs_eps=0, rel_eps=eps) assert hermite(2+3j, -1-j).ae(851.3677063883687676 - 1496.4373467871007997j) def test_gegenbauer(): mp.dps = 15 assert gegenbauer(1,2,3).ae(12) assert gegenbauer(2,3,4).ae(381) assert gegenbauer(0,0,0) == 0 assert gegenbauer(2,-1,3) == 0 assert gegenbauer(-7, 0.5, 3).ae(8989) assert gegenbauer(1, -0.5, 3).ae(-3) assert gegenbauer(1, -1.5, 3).ae(-9) assert gegenbauer(1, -0.5, 3).ae(-3) assert gegenbauer(-0.5, -0.5, 3).ae(-2.6383553159023906245) assert gegenbauer(2+3j, 1-j, 3+4j).ae(14.880536623203696780 + 20.022029711598032898j) #assert gegenbauer(-2, -0.5, 3).ae(-12) def test_legenp(): mp.dps = 15 assert legenp(2,0,4) == legendre(2,4) assert legenp(-2, -1, 0.5).ae(0.43301270189221932338) assert legenp(-2, -1, 0.5, type=3).ae(0.43301270189221932338j) assert legenp(-2, 1, 0.5).ae(-0.86602540378443864676) assert legenp(2+j, 3+4j, -j).ae(134742.98773236786148 + 429782.72924463851745j) assert legenp(2+j, 3+4j, -j, type=3).ae(802.59463394152268507 - 251.62481308942906447j) assert legenp(2,4,3).ae(0) assert legenp(2,4,3,type=3).ae(0) assert legenp(2,1,0.5).ae(-1.2990381056766579701) assert legenp(2,1,0.5,type=3).ae(1.2990381056766579701j) assert legenp(3,2,3).ae(-360) assert legenp(3,3,3).ae(240j*2**0.5) assert legenp(3,4,3).ae(0) assert legenp(0,0.5,2).ae(0.52503756790433198939 - 0.52503756790433198939j) assert legenp(-1,-0.5,2).ae(0.60626116232846498110 + 0.60626116232846498110j) assert legenp(-2,0.5,2).ae(1.5751127037129959682 - 1.5751127037129959682j) assert legenp(-2,0.5,-0.5).ae(-0.85738275810499171286) def test_legenq(): mp.dps = 15 f = legenq # Evaluation at poles assert isnan(f(3,2,1)) assert isnan(f(3,2,-1)) assert isnan(f(3,2,1,type=3)) assert isnan(f(3,2,-1,type=3)) # Evaluation at 0 assert f(0,1,0,type=2).ae(-1) assert f(-2,2,0,type=2,zeroprec=200).ae(0) assert f(1.5,3,0,type=2).ae(-2.2239343475841951023) assert f(0,1,0,type=3).ae(j) assert f(-2,2,0,type=3,zeroprec=200).ae(0) assert f(1.5,3,0,type=3).ae(2.2239343475841951022*(1-1j)) # Standard case, degree 0 assert f(0,0,-1.5).ae(-0.8047189562170501873 + 1.5707963267948966192j) assert f(0,0,-0.5).ae(-0.54930614433405484570) assert f(0,0,0,zeroprec=200).ae(0) assert f(0,0,0.5).ae(0.54930614433405484570) assert f(0,0,1.5).ae(0.8047189562170501873 - 1.5707963267948966192j) assert f(0,0,-1.5,type=3).ae(-0.80471895621705018730) assert f(0,0,-0.5,type=3).ae(-0.5493061443340548457 - 1.5707963267948966192j) assert f(0,0,0,type=3).ae(-1.5707963267948966192j) assert f(0,0,0.5,type=3).ae(0.5493061443340548457 - 1.5707963267948966192j) assert f(0,0,1.5,type=3).ae(0.80471895621705018730) # Standard case, degree 1 assert f(1,0,-1.5).ae(0.2070784343255752810 - 2.3561944901923449288j) assert f(1,0,-0.5).ae(-0.72534692783297257715) assert f(1,0,0).ae(-1) assert f(1,0,0.5).ae(-0.72534692783297257715) assert f(1,0,1.5).ae(0.2070784343255752810 - 2.3561944901923449288j) # Standard case, degree 2 assert f(2,0,-1.5).ae(-0.0635669991240192885 + 4.5160394395353277803j) assert f(2,0,-0.5).ae(0.81866326804175685571) assert f(2,0,0,zeroprec=200).ae(0) assert f(2,0,0.5).ae(-0.81866326804175685571) assert f(2,0,1.5).ae(0.0635669991240192885 - 4.5160394395353277803j) # Misc orders and degrees assert f(2,3,1.5,type=2).ae(-5.7243340223994616228j) assert f(2,3,1.5,type=3).ae(-5.7243340223994616228) assert f(2,3,0.5,type=2).ae(-12.316805742712016310) assert f(2,3,0.5,type=3).ae(-12.316805742712016310j) assert f(2,3,-1.5,type=2).ae(-5.7243340223994616228j) assert f(2,3,-1.5,type=3).ae(5.7243340223994616228) assert f(2,3,-0.5,type=2).ae(-12.316805742712016310) assert f(2,3,-0.5,type=3).ae(-12.316805742712016310j) assert f(2+3j, 3+4j, 0.5, type=3).ae(0.0016119404873235186807 - 0.0005885900510718119836j) assert f(2+3j, 3+4j, -1.5, type=3).ae(0.008451400254138808670 + 0.020645193304593235298j) assert f(-2.5,1,-1.5).ae(3.9553395527435335749j) assert f(-2.5,1,-0.5).ae(1.9290561746445456908) assert f(-2.5,1,0).ae(1.2708196271909686299) assert f(-2.5,1,0.5).ae(-0.31584812990742202869) assert f(-2.5,1,1.5).ae(-3.9553395527435335742 + 0.2993235655044701706j) assert f(-2.5,1,-1.5,type=3).ae(0.29932356550447017254j) assert f(-2.5,1,-0.5,type=3).ae(-0.3158481299074220287 - 1.9290561746445456908j) assert f(-2.5,1,0,type=3).ae(1.2708196271909686292 - 1.2708196271909686299j) assert f(-2.5,1,0.5,type=3).ae(1.9290561746445456907 + 0.3158481299074220287j) assert f(-2.5,1,1.5,type=3).ae(-0.29932356550447017254) def test_agm(): mp.dps = 15 assert agm(0,0) == 0 assert agm(0,1) == 0 assert agm(1,1) == 1 assert agm(7,7) == 7 assert agm(j,j) == j assert (1/agm(1,sqrt(2))).ae(0.834626841674073186) assert agm(1,2).ae(1.4567910310469068692) assert agm(1,3).ae(1.8636167832448965424) assert agm(1,j).ae(0.599070117367796104+0.599070117367796104j) assert agm(2) == agm(1,2) assert agm(-3,4).ae(0.63468509766550907+1.3443087080896272j) def test_gammainc(): mp.dps = 15 assert gammainc(2,5).ae(6*exp(-5)) assert gammainc(2,0,5).ae(1-6*exp(-5)) assert gammainc(2,3,5).ae(-6*exp(-5)+4*exp(-3)) assert gammainc(-2.5,-0.5).ae(-0.9453087204829418812-5.3164237738936178621j) assert gammainc(0,2,4).ae(0.045121158298212213088) assert gammainc(0,3).ae(0.013048381094197037413) assert gammainc(0,2+j,1-j).ae(0.00910653685850304839-0.22378752918074432574j) assert gammainc(0,1-j).ae(0.00028162445198141833+0.17932453503935894015j) assert gammainc(3,4,5,True).ae(0.11345128607046320253) assert gammainc(3.5,0,inf).ae(gamma(3.5)) assert gammainc(-150.5,500).ae('6.9825435345798951153e-627') assert gammainc(-150.5,800).ae('4.6885137549474089431e-788') assert gammainc(-3.5, -20.5).ae(0.27008820585226911 - 1310.31447140574997636j) assert gammainc(-3.5, -200.5).ae(0.27008820585226911 - 5.3264597096208368435e76j) # XXX real part assert gammainc(0,0,2) == inf assert gammainc(1,b=1).ae(0.6321205588285576784) assert gammainc(3,2,2) == 0 assert gammainc(2,3+j,3-j).ae(-0.28135485191849314194j) assert gammainc(4+0j,1).ae(5.8860710587430771455) # GH issue #301 assert gammainc(-1,-1).ae(-0.8231640121031084799 + 3.1415926535897932385j) assert gammainc(-2,-1).ae(1.7707229202810768576 - 1.5707963267948966192j) assert gammainc(-3,-1).ae(-1.4963349162467073643 + 0.5235987755982988731j) assert gammainc(-4,-1).ae(1.05365418617643814992 - 0.13089969389957471827j) # Regularized upper gamma assert isnan(gammainc(0, 0, regularized=True)) assert gammainc(-1, 0, regularized=True) == inf assert gammainc(1, 0, regularized=True) == 1 assert gammainc(0, 5, regularized=True) == 0 assert gammainc(0, 2+3j, regularized=True) == 0 assert gammainc(0, 5000, regularized=True) == 0 assert gammainc(0, 10**30, regularized=True) == 0 assert gammainc(-1, 5, regularized=True) == 0 assert gammainc(-1, 5000, regularized=True) == 0 assert gammainc(-1, 10**30, regularized=True) == 0 assert gammainc(-1, -5, regularized=True) == 0 assert gammainc(-1, -5000, regularized=True) == 0 assert gammainc(-1, -10**30, regularized=True) == 0 assert gammainc(-1, 3+4j, regularized=True) == 0 assert gammainc(1, 5, regularized=True).ae(exp(-5)) assert gammainc(1, 5000, regularized=True).ae(exp(-5000)) assert gammainc(1, 10**30, regularized=True).ae(exp(-10**30)) assert gammainc(1, 3+4j, regularized=True).ae(exp(-3-4j)) assert gammainc(-1000000,2).ae('1.3669297209397347754e-301037', abs_eps=0, rel_eps=8*eps) assert gammainc(-1000000,2,regularized=True) == 0 assert gammainc(-1000000,3+4j).ae('-1.322575609404222361e-698979 - 4.9274570591854533273e-698978j', abs_eps=0, rel_eps=8*eps) assert gammainc(-1000000,3+4j,regularized=True) == 0 assert gammainc(2+3j, 4+5j, regularized=True).ae(0.085422013530993285774-0.052595379150390078503j) assert gammainc(1000j, 1000j, regularized=True).ae(0.49702647628921131761 + 0.00297355675013575341j) # Generalized assert gammainc(3,4,2) == -gammainc(3,2,4) assert gammainc(4, 2, 3).ae(1.2593494302978947396) assert gammainc(4, 2, 3, regularized=True).ae(0.20989157171631578993) assert gammainc(0, 2, 3).ae(0.035852129613864082155) assert gammainc(0, 2, 3, regularized=True) == 0 assert gammainc(-1, 2, 3).ae(0.015219822548487616132) assert gammainc(-1, 2, 3, regularized=True) == 0 assert gammainc(0, 2, 3).ae(0.035852129613864082155) assert gammainc(0, 2, 3, regularized=True) == 0 # Should use upper gammas assert gammainc(5, 10000, 12000).ae('1.1359381951461801687e-4327', abs_eps=0, rel_eps=8*eps) # Should use lower gammas assert gammainc(10000, 2, 3).ae('8.1244514125995785934e4765') # GH issue 306 assert gammainc(3,-1-1j) == 0 assert gammainc(3,-1+1j) == 0 assert gammainc(2,-1) == 0 assert gammainc(2,-1+0j) == 0 assert gammainc(2+0j,-1) == 0 def test_gammainc_expint_n(): # These tests are intended to check all cases of the low-level code # for upper gamma and expint with small integer index. # Need to cover positive/negative arguments; small/large/huge arguments # for both positive and negative indices, as well as indices 0 and 1 # which may be special-cased mp.dps = 15 assert expint(-3,3.5).ae(0.021456366563296693987) assert expint(-2,3.5).ae(0.014966633183073309405) assert expint(-1,3.5).ae(0.011092916359219041088) assert expint(0,3.5).ae(0.0086278238349481430685) assert expint(1,3.5).ae(0.0069701398575483929193) assert expint(2,3.5).ae(0.0058018939208991255223) assert expint(3,3.5).ae(0.0049453773495857807058) assert expint(-3,-3.5).ae(-4.6618170604073311319) assert expint(-2,-3.5).ae(-5.5996974157555515963) assert expint(-1,-3.5).ae(-6.7582555017739415818) assert expint(0,-3.5).ae(-9.4615577024835182145) assert expint(1,-3.5).ae(-13.925353995152335292 - 3.1415926535897932385j) assert expint(2,-3.5).ae(-15.62328702434085977 - 10.995574287564276335j) assert expint(3,-3.5).ae(-10.783026313250347722 - 19.242255003237483586j) assert expint(-3,350).ae(2.8614825451252838069e-155, abs_eps=0, rel_eps=8*eps) assert expint(-2,350).ae(2.8532837224504675901e-155, abs_eps=0, rel_eps=8*eps) assert expint(-1,350).ae(2.8451316155828634555e-155, abs_eps=0, rel_eps=8*eps) assert expint(0,350).ae(2.8370258275042797989e-155, abs_eps=0, rel_eps=8*eps) assert expint(1,350).ae(2.8289659656701459404e-155, abs_eps=0, rel_eps=8*eps) assert expint(2,350).ae(2.8209516419468505006e-155, abs_eps=0, rel_eps=8*eps) assert expint(3,350).ae(2.8129824725501272171e-155, abs_eps=0, rel_eps=8*eps) assert expint(-3,-350).ae(-2.8528796154044839443e+149) assert expint(-2,-350).ae(-2.8610072121701264351e+149) assert expint(-1,-350).ae(-2.8691813842677537647e+149) assert expint(0,-350).ae(-2.8774025343659421709e+149) u = expint(1,-350) assert u.ae(-2.8856710698020863568e+149) assert u.imag.ae(-3.1415926535897932385) u = expint(2,-350) assert u.ae(-2.8939874026504650534e+149) assert u.imag.ae(-1099.5574287564276335) u = expint(3,-350) assert u.ae(-2.9023519497915044349e+149) assert u.imag.ae(-192422.55003237483586) assert expint(-3,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) assert expint(-2,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) assert expint(-1,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) assert expint(0,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) assert expint(1,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) assert expint(2,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) assert expint(3,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) assert expint(-3,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871') assert expint(-2,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871') assert expint(-1,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871') assert expint(0,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871') u = expint(1,-350000000000000000000000) assert u.ae('-3.7805306852415755699e+152003068666138139677871') assert u.imag.ae(-3.1415926535897932385) u = expint(2,-350000000000000000000000) assert u.imag.ae(-1.0995574287564276335e+24) assert u.ae('-3.7805306852415755699e+152003068666138139677871') u = expint(3,-350000000000000000000000) assert u.imag.ae(-1.9242255003237483586e+47) assert u.ae('-3.7805306852415755699e+152003068666138139677871') # Small case; no branch cut assert gammainc(-3,3.5).ae(0.00010020262545203707109) assert gammainc(-2,3.5).ae(0.00040370427343557393517) assert gammainc(-1,3.5).ae(0.0016576839773997501492) assert gammainc(0,3.5).ae(0.0069701398575483929193) assert gammainc(1,3.5).ae(0.03019738342231850074) assert gammainc(2,3.5).ae(0.13588822540043325333) assert gammainc(3,3.5).ae(0.64169439772426814072) # Small case; with branch cut assert gammainc(-3,-3.5).ae(0.03595832954467563286 + 0.52359877559829887308j) assert gammainc(-2,-3.5).ae(-0.88024704597962022221 - 1.5707963267948966192j) assert gammainc(-1,-3.5).ae(4.4637962926688170771 + 3.1415926535897932385j) assert gammainc(0,-3.5).ae(-13.925353995152335292 - 3.1415926535897932385j) assert gammainc(1,-3.5).ae(33.115451958692313751) assert gammainc(2,-3.5).ae(-82.788629896730784377) assert gammainc(3,-3.5).ae(240.08702670051927469) # Asymptotic case; no branch cut assert gammainc(-3,350).ae(6.5424095113340358813e-163, abs_eps=0, rel_eps=8*eps) assert gammainc(-2,350).ae(2.296312222489899769e-160, abs_eps=0, rel_eps=8*eps) assert gammainc(-1,350).ae(8.059861834133858573e-158, abs_eps=0, rel_eps=8*eps) assert gammainc(0,350).ae(2.8289659656701459404e-155, abs_eps=0, rel_eps=8*eps) assert gammainc(1,350).ae(9.9295903962649792963e-153, abs_eps=0, rel_eps=8*eps) assert gammainc(2,350).ae(3.485286229089007733e-150, abs_eps=0, rel_eps=8*eps) assert gammainc(3,350).ae(1.2233453960006379793e-147, abs_eps=0, rel_eps=8*eps) # Asymptotic case; branch cut u = gammainc(-3,-350) assert u.ae(6.7889565783842895085e+141) assert u.imag.ae(0.52359877559829887308) u = gammainc(-2,-350) assert u.ae(-2.3692668977889832121e+144) assert u.imag.ae(-1.5707963267948966192) u = gammainc(-1,-350) assert u.ae(8.2685354361441858669e+146) assert u.imag.ae(3.1415926535897932385) u = gammainc(0,-350) assert u.ae(-2.8856710698020863568e+149) assert u.imag.ae(-3.1415926535897932385) u = gammainc(1,-350) assert u.ae(1.0070908870280797598e+152) assert u.imag == 0 u = gammainc(2,-350) assert u.ae(-3.5147471957279983618e+154) assert u.imag == 0 u = gammainc(3,-350) assert u.ae(1.2266568422179417091e+157) assert u.imag == 0 # Extreme asymptotic case assert gammainc(-3,350000000000000000000000).ae('5.0362468738874738859e-152003068666138139677990', abs_eps=0, rel_eps=8*eps) assert gammainc(-2,350000000000000000000000).ae('1.7626864058606158601e-152003068666138139677966', abs_eps=0, rel_eps=8*eps) assert gammainc(-1,350000000000000000000000).ae('6.1694024205121555102e-152003068666138139677943', abs_eps=0, rel_eps=8*eps) assert gammainc(0,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps) assert gammainc(1,350000000000000000000000).ae('7.5575179651273905e-152003068666138139677896', abs_eps=0, rel_eps=8*eps) assert gammainc(2,350000000000000000000000).ae('2.645131287794586675e-152003068666138139677872', abs_eps=0, rel_eps=8*eps) assert gammainc(3,350000000000000000000000).ae('9.2579595072810533625e-152003068666138139677849', abs_eps=0, rel_eps=8*eps) u = gammainc(-3,-350000000000000000000000) assert u.ae('8.8175642804468234866e+152003068666138139677800') assert u.imag.ae(0.52359877559829887308) u = gammainc(-2,-350000000000000000000000) assert u.ae('-3.0861474981563882203e+152003068666138139677824') assert u.imag.ae(-1.5707963267948966192) u = gammainc(-1,-350000000000000000000000) assert u.ae('1.0801516243547358771e+152003068666138139677848') assert u.imag.ae(3.1415926535897932385) u = gammainc(0,-350000000000000000000000) assert u.ae('-3.7805306852415755699e+152003068666138139677871') assert u.imag.ae(-3.1415926535897932385) assert gammainc(1,-350000000000000000000000).ae('1.3231857398345514495e+152003068666138139677895') assert gammainc(2,-350000000000000000000000).ae('-4.6311500894209300731e+152003068666138139677918') assert gammainc(3,-350000000000000000000000).ae('1.6209025312973255256e+152003068666138139677942') def test_incomplete_beta(): mp.dps = 15 assert betainc(-2,-3,0.5,0.75).ae(63.4305673311255413583969) assert betainc(4.5,0.5+2j,2.5,6).ae(0.2628801146130621387903065 + 0.5162565234467020592855378j) assert betainc(4,5,0,6).ae(90747.77142857142857142857) def test_erf(): mp.dps = 15 assert erf(0) == 0 assert erf(1).ae(0.84270079294971486934) assert erf(3+4j).ae(-120.186991395079444098 - 27.750337293623902498j) assert erf(-4-3j).ae(-0.99991066178539168236 + 0.00004972026054496604j) assert erf(pi).ae(0.99999112385363235839) assert erf(1j).ae(1.6504257587975428760j) assert erf(-1j).ae(-1.6504257587975428760j) assert isinstance(erf(1), mpf) assert isinstance(erf(-1), mpf) assert isinstance(erf(0), mpf) assert isinstance(erf(0j), mpc) assert erf(inf) == 1 assert erf(-inf) == -1 assert erfi(0) == 0 assert erfi(1/pi).ae(0.371682698493894314) assert erfi(inf) == inf assert erfi(-inf) == -inf assert erf(1+0j) == erf(1) assert erfc(1+0j) == erfc(1) assert erf(0.2+0.5j).ae(1 - erfc(0.2+0.5j)) assert erfc(0) == 1 assert erfc(1).ae(1-erf(1)) assert erfc(-1).ae(1-erf(-1)) assert erfc(1/pi).ae(1-erf(1/pi)) assert erfc(-10) == 2 assert erfc(-1000000) == 2 assert erfc(-inf) == 2 assert erfc(inf) == 0 assert isnan(erfc(nan)) assert (erfc(10**4)*mpf(10)**43429453).ae('3.63998738656420') assert erf(8+9j).ae(-1072004.2525062051158 + 364149.91954310255423j) assert erfc(8+9j).ae(1072005.2525062051158 - 364149.91954310255423j) assert erfc(-8-9j).ae(-1072003.2525062051158 + 364149.91954310255423j) mp.dps = 50 # This one does not use the asymptotic series assert (erfc(10)*10**45).ae('2.0884875837625447570007862949577886115608181193212') # This one does assert (erfc(50)*10**1088).ae('2.0709207788416560484484478751657887929322509209954') mp.dps = 15 assert str(erfc(10**50)) == '3.66744826532555e-4342944819032518276511289189166050822943970058036665661144537831658646492088707747292249493384317534' assert erfinv(0) == 0 assert erfinv(0.5).ae(0.47693627620446987338) assert erfinv(-0.5).ae(-0.47693627620446987338) assert erfinv(1) == inf assert erfinv(-1) == -inf assert erf(erfinv(0.95)).ae(0.95) assert erf(erfinv(0.999999999995)).ae(0.999999999995) assert erf(erfinv(-0.999999999995)).ae(-0.999999999995) mp.dps = 50 assert erf(erfinv('0.99999999999999999999999999999995')).ae('0.99999999999999999999999999999995') assert erf(erfinv('0.999999999999999999999999999999995')).ae('0.999999999999999999999999999999995') assert erf(erfinv('-0.999999999999999999999999999999995')).ae('-0.999999999999999999999999999999995') mp.dps = 15 # Complex asymptotic expansions v = erfc(50j) assert v.real == 1 assert v.imag.ae('-6.1481820666053078736e+1083') assert erfc(-100+5j).ae(2) assert (erfc(100+5j)*10**4335).ae(2.3973567853824133572 - 3.9339259530609420597j) assert erfc(100+100j).ae(0.00065234366376857698698 - 0.0039357263629214118437j) def test_pdf(): mp.dps = 15 assert npdf(-inf) == 0 assert npdf(inf) == 0 assert npdf(5,0,2).ae(npdf(5+4,4,2)) assert quadts(lambda x: npdf(x,-0.5,0.8), [-inf, inf]) == 1 assert ncdf(0) == 0.5 assert ncdf(3,3) == 0.5 assert ncdf(-inf) == 0 assert ncdf(inf) == 1 assert ncdf(10) == 1 # Verify that this is computed accurately assert (ncdf(-10)*10**24).ae(7.619853024160526) def test_lambertw(): mp.dps = 15 assert lambertw(0) == 0 assert lambertw(0+0j) == 0 assert lambertw(inf) == inf assert isnan(lambertw(nan)) assert lambertw(inf,1).real == inf assert lambertw(inf,1).imag.ae(2*pi) assert lambertw(-inf,1).real == inf assert lambertw(-inf,1).imag.ae(3*pi) assert lambertw(0,-1) == -inf assert lambertw(0,1) == -inf assert lambertw(0,3) == -inf assert lambertw(e).ae(1) assert lambertw(1).ae(0.567143290409783873) assert lambertw(-pi/2).ae(j*pi/2) assert lambertw(-log(2)/2).ae(-log(2)) assert lambertw(0.25).ae(0.203888354702240164) assert lambertw(-0.25).ae(-0.357402956181388903) assert lambertw(-1./10000,0).ae(-0.000100010001500266719) assert lambertw(-0.25,-1).ae(-2.15329236411034965) assert lambertw(0.25,-1).ae(-3.00899800997004620-4.07652978899159763j) assert lambertw(-0.25,-1).ae(-2.15329236411034965) assert lambertw(0.25,1).ae(-3.00899800997004620+4.07652978899159763j) assert lambertw(-0.25,1).ae(-3.48973228422959210+7.41405453009603664j) assert lambertw(-4).ae(0.67881197132094523+1.91195078174339937j) assert lambertw(-4,1).ae(-0.66743107129800988+7.76827456802783084j) assert lambertw(-4,-1).ae(0.67881197132094523-1.91195078174339937j) assert lambertw(1000).ae(5.24960285240159623) assert lambertw(1000,1).ae(4.91492239981054535+5.44652615979447070j) assert lambertw(1000,-1).ae(4.91492239981054535-5.44652615979447070j) assert lambertw(1000,5).ae(3.5010625305312892+29.9614548941181328j) assert lambertw(3+4j).ae(1.281561806123775878+0.533095222020971071j) assert lambertw(-0.4+0.4j).ae(-0.10396515323290657+0.61899273315171632j) assert lambertw(3+4j,1).ae(-0.11691092896595324+5.61888039871282334j) assert lambertw(3+4j,-1).ae(0.25856740686699742-3.85211668616143559j) assert lambertw(-0.5,-1).ae(-0.794023632344689368-0.770111750510379110j) assert lambertw(-1./10000,1).ae(-11.82350837248724344+6.80546081842002101j) assert lambertw(-1./10000,-1).ae(-11.6671145325663544) assert lambertw(-1./10000,-2).ae(-11.82350837248724344-6.80546081842002101j) assert lambertw(-1./100000,4).ae(-14.9186890769540539+26.1856750178782046j) assert lambertw(-1./100000,5).ae(-15.0931437726379218666+32.5525721210262290086j) assert lambertw((2+j)/10).ae(0.173704503762911669+0.071781336752835511j) assert lambertw((2+j)/10,1).ae(-3.21746028349820063+4.56175438896292539j) assert lambertw((2+j)/10,-1).ae(-3.03781405002993088-3.53946629633505737j) assert lambertw((2+j)/10,4).ae(-4.6878509692773249+23.8313630697683291j) assert lambertw(-(2+j)/10).ae(-0.226933772515757933-0.164986470020154580j) assert lambertw(-(2+j)/10,1).ae(-2.43569517046110001+0.76974067544756289j) assert lambertw(-(2+j)/10,-1).ae(-3.54858738151989450-6.91627921869943589j) assert lambertw(-(2+j)/10,4).ae(-4.5500846928118151+20.6672982215434637j) mp.dps = 50 assert lambertw(pi).ae('1.073658194796149172092178407024821347547745350410314531') mp.dps = 15 # Former bug in generated branch assert lambertw(-0.5+0.002j).ae(-0.78917138132659918344 + 0.76743539379990327749j) assert lambertw(-0.5-0.002j).ae(-0.78917138132659918344 - 0.76743539379990327749j) assert lambertw(-0.448+0.4j).ae(-0.11855133765652382241 + 0.66570534313583423116j) assert lambertw(-0.448-0.4j).ae(-0.11855133765652382241 - 0.66570534313583423116j) assert lambertw(-0.65475+0.0001j).ae(-0.61053421111385310898+1.0396534993944097723803j) # Huge branch index w = lambertw(1,10**20) assert w.real.ae(-47.889578926290259164) assert w.imag.ae(6.2831853071795864769e+20) def test_lambertw_hard(): def check(x,y): y = convert(y) type_ok = True if isinstance(y, mpf): type_ok = isinstance(x, mpf) real_ok = abs(x.real-y.real) <= abs(y.real)*8*eps imag_ok = abs(x.imag-y.imag) <= abs(y.imag)*8*eps #print x, y, abs(x.real-y.real), abs(x.imag-y.imag) return real_ok and imag_ok # Evaluation near 0 mp.dps = 15 assert check(lambertw(1e-10), 9.999999999000000000e-11) assert check(lambertw(-1e-10), -1.000000000100000000e-10) assert check(lambertw(1e-10j), 9.999999999999999999733e-21 + 9.99999999999999999985e-11j) assert check(lambertw(-1e-10j), 9.999999999999999999733e-21 - 9.99999999999999999985e-11j) assert check(lambertw(1e-10,1), -26.303186778379041559 + 3.265093911703828397j) assert check(lambertw(-1e-10,1), -26.326236166739163892 + 6.526183280686333315j) assert check(lambertw(1e-10j,1), -26.312931726911421551 + 4.896366881798013421j) assert check(lambertw(-1e-10j,1), -26.297238779529035066 + 1.632807161345576513j) assert check(lambertw(1e-10,-1), -26.303186778379041559 - 3.265093911703828397j) assert check(lambertw(-1e-10,-1), -26.295238819246925694) assert check(lambertw(1e-10j,-1), -26.297238779529035028 - 1.6328071613455765135j) assert check(lambertw(-1e-10j,-1), -26.312931726911421551 - 4.896366881798013421j) # Test evaluation very close to the branch point -1/e # on the -1, 0, and 1 branches add = lambda x, y: fadd(x,y,exact=True) sub = lambda x, y: fsub(x,y,exact=True) addj = lambda x, y: fadd(x,fmul(y,1j,exact=True),exact=True) subj = lambda x, y: fadd(x,fmul(y,-1j,exact=True),exact=True) mp.dps = 1500 a = -1/e + 10*eps d3 = mpf('1e-3') d10 = mpf('1e-10') d20 = mpf('1e-20') d40 = mpf('1e-40') d80 = mpf('1e-80') d300 = mpf('1e-300') d1000 = mpf('1e-1000') mp.dps = 15 # ---- Branch 0 ---- # -1/e + eps assert check(lambertw(add(a,d3)), -0.92802015005456704876) assert check(lambertw(add(a,d10)), -0.99997668374140088071) assert check(lambertw(add(a,d20)), -0.99999999976683560186) assert lambertw(add(a,d40)) == -1 assert lambertw(add(a,d80)) == -1 assert lambertw(add(a,d300)) == -1 assert lambertw(add(a,d1000)) == -1 # -1/e - eps assert check(lambertw(sub(a,d3)), -0.99819016149860989001+0.07367191188934638577j) assert check(lambertw(sub(a,d10)), -0.9999999998187812114595992+0.0000233164398140346109194j) assert check(lambertw(sub(a,d20)), -0.99999999999999999998187+2.331643981597124203344e-10j) assert check(lambertw(sub(a,d40)), -1.0+2.33164398159712420336e-20j) assert check(lambertw(sub(a,d80)), -1.0+2.33164398159712420336e-40j) assert check(lambertw(sub(a,d300)), -1.0+2.33164398159712420336e-150j) assert check(lambertw(sub(a,d1000)), mpc(-1,'2.33164398159712420336e-500')) # -1/e + eps*j assert check(lambertw(addj(a,d3)), -0.94790387486938526634+0.05036819639190132490j) assert check(lambertw(addj(a,d10)), -0.9999835127872943680999899+0.0000164870314895821225256j) assert check(lambertw(addj(a,d20)), -0.999999999835127872929987+1.64872127051890935830e-10j) assert check(lambertw(addj(a,d40)), -0.9999999999999999999835+1.6487212707001281468305e-20j) assert check(lambertw(addj(a,d80)), -1.0 + 1.64872127070012814684865e-40j) assert check(lambertw(addj(a,d300)), -1.0 + 1.64872127070012814684865e-150j) assert check(lambertw(addj(a,d1000)), mpc(-1.0,'1.64872127070012814684865e-500')) # -1/e - eps*j assert check(lambertw(subj(a,d3)), -0.94790387486938526634-0.05036819639190132490j) assert check(lambertw(subj(a,d10)), -0.9999835127872943680999899-0.0000164870314895821225256j) assert check(lambertw(subj(a,d20)), -0.999999999835127872929987-1.64872127051890935830e-10j) assert check(lambertw(subj(a,d40)), -0.9999999999999999999835-1.6487212707001281468305e-20j) assert check(lambertw(subj(a,d80)), -1.0 - 1.64872127070012814684865e-40j) assert check(lambertw(subj(a,d300)), -1.0 - 1.64872127070012814684865e-150j) assert check(lambertw(subj(a,d1000)), mpc(-1.0,'-1.64872127070012814684865e-500')) # ---- Branch 1 ---- assert check(lambertw(addj(a,d3),1), -3.088501303219933378005990 + 7.458676867597474813950098j) assert check(lambertw(addj(a,d80),1), -3.088843015613043855957087 + 7.461489285654254556906117j) assert check(lambertw(addj(a,d300),1), -3.088843015613043855957087 + 7.461489285654254556906117j) assert check(lambertw(addj(a,d1000),1), -3.088843015613043855957087 + 7.461489285654254556906117j) assert check(lambertw(subj(a,d3),1), -1.0520914180450129534365906 + 0.0539925638125450525673175j) assert check(lambertw(subj(a,d10),1), -1.0000164872127056318529390 + 0.000016487393927159250398333077j) assert check(lambertw(subj(a,d20),1), -1.0000000001648721270700128 + 1.64872127088134693542628e-10j) assert check(lambertw(subj(a,d40),1), -1.000000000000000000016487 + 1.64872127070012814686677e-20j) assert check(lambertw(subj(a,d80),1), -1.0 + 1.64872127070012814684865e-40j) assert check(lambertw(subj(a,d300),1), -1.0 + 1.64872127070012814684865e-150j) assert check(lambertw(subj(a,d1000),1), mpc(-1.0, '1.64872127070012814684865e-500')) # ---- Branch -1 ---- # -1/e + eps assert check(lambertw(add(a,d3),-1), -1.075608941186624989414945) assert check(lambertw(add(a,d10),-1), -1.000023316621036696460620) assert check(lambertw(add(a,d20),-1), -1.000000000233164398177834) assert lambertw(add(a,d40),-1) == -1 assert lambertw(add(a,d80),-1) == -1 assert lambertw(add(a,d300),-1) == -1 assert lambertw(add(a,d1000),-1) == -1 # -1/e - eps assert check(lambertw(sub(a,d3),-1), -0.99819016149860989001-0.07367191188934638577j) assert check(lambertw(sub(a,d10),-1), -0.9999999998187812114595992-0.0000233164398140346109194j) assert check(lambertw(sub(a,d20),-1), -0.99999999999999999998187-2.331643981597124203344e-10j) assert check(lambertw(sub(a,d40),-1), -1.0-2.33164398159712420336e-20j) assert check(lambertw(sub(a,d80),-1), -1.0-2.33164398159712420336e-40j) assert check(lambertw(sub(a,d300),-1), -1.0-2.33164398159712420336e-150j) assert check(lambertw(sub(a,d1000),-1), mpc(-1,'-2.33164398159712420336e-500')) # -1/e + eps*j assert check(lambertw(addj(a,d3),-1), -1.0520914180450129534365906 - 0.0539925638125450525673175j) assert check(lambertw(addj(a,d10),-1), -1.0000164872127056318529390 - 0.0000164873939271592503983j) assert check(lambertw(addj(a,d20),-1), -1.0000000001648721270700 - 1.64872127088134693542628e-10j) assert check(lambertw(addj(a,d40),-1), -1.00000000000000000001648 - 1.6487212707001281468667726e-20j) assert check(lambertw(addj(a,d80),-1), -1.0 - 1.64872127070012814684865e-40j) assert check(lambertw(addj(a,d300),-1), -1.0 - 1.64872127070012814684865e-150j) assert check(lambertw(addj(a,d1000),-1), mpc(-1.0,'-1.64872127070012814684865e-500')) # -1/e - eps*j assert check(lambertw(subj(a,d3),-1), -3.088501303219933378005990-7.458676867597474813950098j) assert check(lambertw(subj(a,d10),-1), -3.088843015579260686911033-7.461489285372968780020716j) assert check(lambertw(subj(a,d20),-1), -3.088843015613043855953708-7.461489285654254556877988j) assert check(lambertw(subj(a,d40),-1), -3.088843015613043855957087-7.461489285654254556906117j) assert check(lambertw(subj(a,d80),-1), -3.088843015613043855957087 - 7.461489285654254556906117j) assert check(lambertw(subj(a,d300),-1), -3.088843015613043855957087 - 7.461489285654254556906117j) assert check(lambertw(subj(a,d1000),-1), -3.088843015613043855957087 - 7.461489285654254556906117j) # One more case, testing higher precision mp.dps = 500 x = -1/e + mpf('1e-13') ans = "-0.99999926266961377166355784455394913638782494543377383"\ "744978844374498153493943725364881490261187530235150668593869563"\ "168276697689459394902153960200361935311512317183678882" mp.dps = 15 assert lambertw(x).ae(ans) mp.dps = 50 assert lambertw(x).ae(ans) mp.dps = 150 assert lambertw(x).ae(ans) def test_meijerg(): mp.dps = 15 assert meijerg([[2,3],[1]],[[0.5,2],[3,4]], 2.5).ae(4.2181028074787439386) assert meijerg([[],[1+j]],[[1],[1]], 3+4j).ae(271.46290321152464592 - 703.03330399954820169j) assert meijerg([[0.25],[1]],[[0.5],[2]],0) == 0 assert meijerg([[0],[]],[[0,0,'1/3','2/3'], []], '2/27').ae(2.2019391389653314120) # Verify 1/z series being used assert meijerg([[-3],[-0.5]], [[-1],[-2.5]], -0.5).ae(-1.338096165935754898687431) assert meijerg([[1-(-1)],[1-(-2.5)]], [[1-(-3)],[1-(-0.5)]], -2.0).ae(-1.338096165935754898687431) assert meijerg([[-3],[-0.5]], [[-1],[-2.5]], -1).ae(-(pi+4)/(4*pi)) a = 2.5 b = 1.25 for z in [mpf(0.25), mpf(2)]: x1 = hyp1f1(a,b,z) x2 = gamma(b)/gamma(a)*meijerg([[1-a],[]],[[0],[1-b]],-z) x3 = gamma(b)/gamma(a)*meijerg([[1-0],[1-(1-b)]],[[1-(1-a)],[]],-1/z) assert x1.ae(x2) assert x1.ae(x3) def test_appellf1(): mp.dps = 15 assert appellf1(2,-2,1,1,2,3).ae(-1.75) assert appellf1(2,1,-2,1,2,3).ae(-8) assert appellf1(2,1,-2,1,0.5,0.25).ae(1.5) assert appellf1(-2,1,3,2,3,3).ae(19) assert appellf1(1,2,3,4,0.5,0.125).ae( 1.53843285792549786518) def test_coulomb(): # Note: most tests are doctests # Test for a bug: mp.dps = 15 assert coulombg(mpc(-5,0),2,3).ae(20.087729487721430394) def test_hyper_param_accuracy(): mp.dps = 15 As = [n+1e-10 for n in range(-5,-1)] Bs = [n+1e-10 for n in range(-12,-5)] assert hyper(As,Bs,10).ae(-381757055858.652671927) assert legenp(0.5, 100, 0.25).ae(-2.4124576567211311755e+144) assert (hyp1f1(1000,1,-100)*10**24).ae(5.2589445437370169113) assert (hyp2f1(10, -900, 10.5, 0.99)*10**24).ae(1.9185370579660768203) assert (hyp2f1(1000,1.5,-3.5,-1.5)*10**385).ae(-2.7367529051334000764) assert hyp2f1(-5, 10, 3, 0.5, zeroprec=500) == 0 assert (hyp1f1(-10000, 1000, 100)*10**424).ae(-3.1046080515824859974) assert (hyp2f1(1000,1.5,-3.5,-0.75,maxterms=100000)*10**231).ae(-4.0534790813913998643) assert legenp(2, 3, 0.25) == 0 try: hypercomb(lambda a: [([],[],[],[],[a],[-a],0.5)], [3]) assert 0 except ValueError: pass assert hypercomb(lambda a: [([],[],[],[],[a],[-a],0.5)], [3], infprec=200) == inf assert meijerg([[],[]],[[0,0,0,0],[]],0.1).ae(1.5680822343832351418) assert (besselk(400,400)*10**94).ae(1.4387057277018550583) mp.dps = 5 (hyp1f1(-5000.5, 1500, 100)*10**185).ae(8.5185229673381935522) (hyp1f1(-5000, 1500, 100)*10**185).ae(9.1501213424563944311) mp.dps = 15 (hyp1f1(-5000.5, 1500, 100)*10**185).ae(8.5185229673381935522) (hyp1f1(-5000, 1500, 100)*10**185).ae(9.1501213424563944311) assert hyp0f1(fadd(-20,'1e-100',exact=True), 0.25).ae(1.85014429040102783e+49) assert hyp0f1((-20*10**100+1, 10**100), 0.25).ae(1.85014429040102783e+49) def test_hypercomb_zero_pow(): # check that 0^0 = 1 assert hypercomb(lambda a: (([0],[a],[],[],[],[],0),), [0]) == 1 assert meijerg([[-1.5],[]],[[0],[-0.75]],0).ae(1.4464090846320771425) def test_spherharm(): mp.dps = 15 t = 0.5; r = 0.25 assert spherharm(0,0,t,r).ae(0.28209479177387814347) assert spherharm(1,-1,t,r).ae(0.16048941205971996369 - 0.04097967481096344271j) assert spherharm(1,0,t,r).ae(0.42878904414183579379) assert spherharm(1,1,t,r).ae(-0.16048941205971996369 - 0.04097967481096344271j) assert spherharm(2,-2,t,r).ae(0.077915886919031181734 - 0.042565643022253962264j) assert spherharm(2,-1,t,r).ae(0.31493387233497459884 - 0.08041582001959297689j) assert spherharm(2,0,t,r).ae(0.41330596756220761898) assert spherharm(2,1,t,r).ae(-0.31493387233497459884 - 0.08041582001959297689j) assert spherharm(2,2,t,r).ae(0.077915886919031181734 + 0.042565643022253962264j) assert spherharm(3,-3,t,r).ae(0.033640236589690881646 - 0.031339125318637082197j) assert spherharm(3,-2,t,r).ae(0.18091018743101461963 - 0.09883168583167010241j) assert spherharm(3,-1,t,r).ae(0.42796713930907320351 - 0.10927795157064962317j) assert spherharm(3,0,t,r).ae(0.27861659336351639787) assert spherharm(3,1,t,r).ae(-0.42796713930907320351 - 0.10927795157064962317j) assert spherharm(3,2,t,r).ae(0.18091018743101461963 + 0.09883168583167010241j) assert spherharm(3,3,t,r).ae(-0.033640236589690881646 - 0.031339125318637082197j) assert spherharm(0,-1,t,r) == 0 assert spherharm(0,-2,t,r) == 0 assert spherharm(0,1,t,r) == 0 assert spherharm(0,2,t,r) == 0 assert spherharm(1,2,t,r) == 0 assert spherharm(1,3,t,r) == 0 assert spherharm(1,-2,t,r) == 0 assert spherharm(1,-3,t,r) == 0 assert spherharm(2,3,t,r) == 0 assert spherharm(2,4,t,r) == 0 assert spherharm(2,-3,t,r) == 0 assert spherharm(2,-4,t,r) == 0 assert spherharm(3,4.5,0.5,0.25).ae(-22.831053442240790148 + 10.910526059510013757j) assert spherharm(2+3j, 1-j, 1+j, 3+4j).ae(-2.6582752037810116935 - 1.0909214905642160211j) assert spherharm(-6,2.5,t,r).ae(0.39383644983851448178 + 0.28414687085358299021j) assert spherharm(-3.5, 3, 0.5, 0.25).ae(0.014516852987544698924 - 0.015582769591477628495j) assert spherharm(-3, 3, 0.5, 0.25) == 0 assert spherharm(-6, 3, 0.5, 0.25).ae(-0.16544349818782275459 - 0.15412657723253924562j) assert spherharm(-6, 1.5, 0.5, 0.25).ae(0.032208193499767402477 + 0.012678000924063664921j) assert spherharm(3,0,0,1).ae(0.74635266518023078283) assert spherharm(3,-2,0,1) == 0 assert spherharm(3,-2,1,1).ae(-0.16270707338254028971 - 0.35552144137546777097j) def test_qfunctions(): mp.dps = 15 assert qp(2,3,100).ae('2.7291482267247332183e2391') def test_issue_239(): mp.prec = 150 x = ldexp(2476979795053773,-52) assert betainc(206, 385, 0, 0.55, 1).ae('0.99999999999999999999996570910644857895771110649954') mp.dps = 15 try: u = hyp2f1(-5,5,0.5,0.5) raise AssertionError("hyp2f1(-5,5,0.5,0.5) (failed zero detection)") except (mp.NoConvergence, ValueError): pass
76,413
51.302533
255
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_eigen_symmetric.py
#!/usr/bin/python # -*- coding: utf-8 -*- from mpmath import mp from mpmath import libmp xrange = libmp.backend.xrange def run_eigsy(A, verbose = False): if verbose: print("original matrix:\n", str(A)) D, Q = mp.eigsy(A) B = Q * mp.diag(D) * Q.transpose() C = A - B E = Q * Q.transpose() - mp.eye(A.rows) if verbose: print("eigenvalues:\n", D) print("eigenvectors:\n", Q) NC = mp.mnorm(C) NE = mp.mnorm(E) if verbose: print("difference:", NC, "\n", C, "\n") print("difference:", NE, "\n", E, "\n") eps = mp.exp( 0.8 * mp.log(mp.eps)) assert NC < eps assert NE < eps return NC def run_eighe(A, verbose = False): if verbose: print("original matrix:\n", str(A)) D, Q = mp.eighe(A) B = Q * mp.diag(D) * Q.transpose_conj() C = A - B E = Q * Q.transpose_conj() - mp.eye(A.rows) if verbose: print("eigenvalues:\n", D) print("eigenvectors:\n", Q) NC = mp.mnorm(C) NE = mp.mnorm(E) if verbose: print("difference:", NC, "\n", C, "\n") print("difference:", NE, "\n", E, "\n") eps = mp.exp( 0.8 * mp.log(mp.eps)) assert NC < eps assert NE < eps return NC def run_svd_r(A, full_matrices = False, verbose = True): m, n = A.rows, A.cols eps = mp.exp(0.8 * mp.log(mp.eps)) if verbose: print("original matrix:\n", str(A)) print("full", full_matrices) U, S0, V = mp.svd_r(A, full_matrices = full_matrices) S = mp.zeros(U.cols, V.rows) for j in xrange(min(m, n)): S[j,j] = S0[j] if verbose: print("U:\n", str(U)) print("S:\n", str(S0)) print("V:\n", str(V)) C = U * S * V - A err = mp.mnorm(C) if verbose: print("C\n", str(C), "\n", err) assert err < eps D = V * V.transpose() - mp.eye(V.rows) err = mp.mnorm(D) if verbose: print("D:\n", str(D), "\n", err) assert err < eps E = U.transpose() * U - mp.eye(U.cols) err = mp.mnorm(E) if verbose: print("E:\n", str(E), "\n", err) assert err < eps def run_svd_c(A, full_matrices = False, verbose = True): m, n = A.rows, A.cols eps = mp.exp(0.8 * mp.log(mp.eps)) if verbose: print("original matrix:\n", str(A)) print("full", full_matrices) U, S0, V = mp.svd_c(A, full_matrices = full_matrices) S = mp.zeros(U.cols, V.rows) for j in xrange(min(m, n)): S[j,j] = S0[j] if verbose: print("U:\n", str(U)) print("S:\n", str(S0)) print("V:\n", str(V)) C = U * S * V - A err = mp.mnorm(C) if verbose: print("C\n", str(C), "\n", err) assert err < eps D = V * V.transpose_conj() - mp.eye(V.rows) err = mp.mnorm(D) if verbose: print("D:\n", str(D), "\n", err) assert err < eps E = U.transpose_conj() * U - mp.eye(U.cols) err = mp.mnorm(E) if verbose: print("E:\n", str(E), "\n", err) assert err < eps def run_gauss(qtype, a, b): eps = 1e-5 d, e = mp.gauss_quadrature(len(a), qtype) d -= mp.matrix(a) e -= mp.matrix(b) assert mp.mnorm(d) < eps assert mp.mnorm(e) < eps def irandmatrix(n, range = 10): """ random matrix with integer entries """ A = mp.matrix(n, n) for i in xrange(n): for j in xrange(n): A[i,j]=int( (2 * mp.rand() - 1) * range) return A ####################### def test_eighe_fixed_matrix(): A = mp.matrix([[2, 3], [3, 5]]) run_eigsy(A) run_eighe(A) A = mp.matrix([[7, -11], [-11, 13]]) run_eigsy(A) run_eighe(A) A = mp.matrix([[2, 11, 7], [11, 3, 13], [7, 13, 5]]) run_eigsy(A) run_eighe(A) A = mp.matrix([[2, 0, 7], [0, 3, 1], [7, 1, 5]]) run_eigsy(A) run_eighe(A) # A = mp.matrix([[2, 3+7j], [3-7j, 5]]) run_eighe(A) A = mp.matrix([[2, -11j, 0], [+11j, 3, 29j], [0, -29j, 5]]) run_eighe(A) A = mp.matrix([[2, 11 + 17j, 7 + 19j], [11 - 17j, 3, -13 + 23j], [7 - 19j, -13 - 23j, 5]]) run_eighe(A) def test_eigsy_randmatrix(): N = 5 for a in xrange(10): A = 2 * mp.randmatrix(N, N) - 1 for i in xrange(0, N): for j in xrange(i + 1, N): A[j,i] = A[i,j] run_eigsy(A) def test_eighe_randmatrix(): N = 5 for a in xrange(10): A = (2 * mp.randmatrix(N, N) - 1) + 1j * (2 * mp.randmatrix(N, N) - 1) for i in xrange(0, N): A[i,i] = mp.re(A[i,i]) for j in xrange(i + 1, N): A[j,i] = mp.conj(A[i,j]) run_eighe(A) def test_eigsy_irandmatrix(): N = 4 R = 4 for a in xrange(10): A=irandmatrix(N, R) for i in xrange(0, N): for j in xrange(i + 1, N): A[j,i] = A[i,j] run_eigsy(A) def test_eighe_irandmatrix(): N = 4 R = 4 for a in xrange(10): A=irandmatrix(N, R) + 1j * irandmatrix(N, R) for i in xrange(0, N): A[i,i] = mp.re(A[i,i]) for j in xrange(i + 1, N): A[j,i] = mp.conj(A[i,j]) run_eighe(A) def test_svd_r_rand(): for i in xrange(5): full = mp.rand() > 0.5 m = 1 + int(mp.rand() * 10) n = 1 + int(mp.rand() * 10) A = 2 * mp.randmatrix(m, n) - 1 if mp.rand() > 0.5: A *= 10 for x in xrange(m): for y in xrange(n): A[x,y]=int(A[x,y]) run_svd_r(A, full_matrices = full, verbose = False) def test_svd_c_rand(): for i in xrange(5): full = mp.rand() > 0.5 m = 1 + int(mp.rand() * 10) n = 1 + int(mp.rand() * 10) A = (2 * mp.randmatrix(m, n) - 1) + 1j * (2 * mp.randmatrix(m, n) - 1) if mp.rand() > 0.5: A *= 10 for x in xrange(m): for y in xrange(n): A[x,y]=int(mp.re(A[x,y])) + 1j * int(mp.im(A[x,y])) run_svd_c(A, full_matrices=full, verbose=False) def test_svd_test_case(): # a test case from Golub and Reinsch # (see wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971).) eps = mp.exp(0.8 * mp.log(mp.eps)) a = [[22, 10, 2, 3, 7], [14, 7, 10, 0, 8], [-1, 13, -1, -11, 3], [-3, -2, 13, -2, 4], [ 9, 8, 1, -2, 4], [ 9, 1, -7, 5, -1], [ 2, -6, 6, 5, 1], [ 4, 5, 0, -2, 2]] a = mp.matrix(a) b = mp.matrix([mp.sqrt(1248), 20, mp.sqrt(384), 0, 0]) S = mp.svd_r(a, compute_uv = False) S -= b assert mp.mnorm(S) < eps S = mp.svd_c(a, compute_uv = False) S -= b assert mp.mnorm(S) < eps def test_gauss_quadrature_static(): a = [-0.57735027, 0.57735027] b = [ 1, 1] run_gauss("legendre", a , b) a = [ -0.906179846, -0.538469310, 0, 0.538469310, 0.906179846] b = [ 0.23692689, 0.47862867, 0.56888889, 0.47862867, 0.23692689] run_gauss("legendre", a , b) a = [ 0.06943184, 0.33000948, 0.66999052, 0.93056816] b = [ 0.17392742, 0.32607258, 0.32607258, 0.17392742] run_gauss("legendre01", a , b) a = [-0.70710678, 0.70710678] b = [ 0.88622693, 0.88622693] run_gauss("hermite", a , b) a = [ -2.02018287, -0.958572465, 0, 0.958572465, 2.02018287] b = [ 0.01995324, 0.39361932, 0.94530872, 0.39361932, 0.01995324] run_gauss("hermite", a , b) a = [ 0.41577456, 2.29428036, 6.28994508] b = [ 0.71109301, 0.27851773, 0.01038926] run_gauss("laguerre", a , b) def test_gauss_quadrature_dynamic(verbose = False): n = 5 A = mp.randmatrix(2 * n, 1) def F(x): r = 0 for i in xrange(len(A) - 1, -1, -1): r = r * x + A[i] return r def run(qtype, FW, R, alpha = 0, beta = 0): X, W = mp.gauss_quadrature(n, qtype, alpha = alpha, beta = beta) a = 0 for i in xrange(len(X)): a += W[i] * F(X[i]) b = mp.quad(lambda x: FW(x) * F(x), R) c = mp.fabs(a - b) if verbose: print(qtype, c, a, b) assert c < 1e-5 run("legendre", lambda x: 1, [-1, 1]) run("legendre01", lambda x: 1, [0, 1]) run("hermite", lambda x: mp.exp(-x*x), [-mp.inf, mp.inf]) run("laguerre", lambda x: mp.exp(-x), [0, mp.inf]) run("glaguerre", lambda x: mp.sqrt(x)*mp.exp(-x), [0, mp.inf], alpha = 1 / mp.mpf(2)) run("chebyshev1", lambda x: 1/mp.sqrt(1-x*x), [-1, 1]) run("chebyshev2", lambda x: mp.sqrt(1-x*x), [-1, 1]) run("jacobi", lambda x: (1-x)**(1/mp.mpf(3)) * (1+x)**(1/mp.mpf(5)), [-1, 1], alpha = 1 / mp.mpf(3), beta = 1 / mp.mpf(5) )
8,778
23.522346
127
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/extratest_gamma.py
from mpmath import * from mpmath.libmp import ifac import sys if "-dps" in sys.argv: maxdps = int(sys.argv[sys.argv.index("-dps")+1]) else: maxdps = 1000 raise_ = "-raise" in sys.argv errcount = 0 def check(name, func, z, y): global errcount try: x = func(z) except: errcount += 1 if raise_: raise print() print(name) print("EXCEPTION") import traceback traceback.print_tb(sys.exc_info()[2]) print() return xre = x.real xim = x.imag yre = y.real yim = y.imag tol = eps*8 err = 0 if abs(xre-yre) > abs(yre)*tol: err = 1 print() print("Error! %s (re = %s, wanted %s, err=%s)" % (name, nstr(xre,10), nstr(yre,10), nstr(abs(xre-yre)))) errcount += 1 if raise_: raise SystemExit if abs(xim-yim) > abs(yim)*tol: err = 1 print() print("Error! %s (im = %s, wanted %s, err=%s)" % (name, nstr(xim,10), nstr(yim,10), nstr(abs(xim-yim)))) errcount += 1 if raise_: raise SystemExit if not err: sys.stdout.write("%s ok; " % name) def testcase(case): z, result = case print("Testing z =", z) mp.dps = 1010 z = eval(z) mp.dps = maxdps + 50 if result is None: gamma_val = gamma(z) loggamma_val = loggamma(z) factorial_val = factorial(z) rgamma_val = rgamma(z) else: loggamma_val = eval(result) gamma_val = exp(loggamma_val) factorial_val = z * gamma_val rgamma_val = 1/gamma_val for dps in [5, 10, 15, 25, 40, 60, 90, 120, 250, 600, 1000, 1800, 3600]: if dps > maxdps: break mp.dps = dps print("dps = %s" % dps) check("gamma", gamma, z, gamma_val) check("rgamma", rgamma, z, rgamma_val) check("loggamma", loggamma, z, loggamma_val) check("factorial", factorial, z, factorial_val) print() mp.dps = 15 testcases = [] # Basic values for n in list(range(1,200)) + list(range(201,2000,17)): testcases.append(["%s" % n, None]) for n in range(-200,200): testcases.append(["%s+0.5" % n, None]) testcases.append(["%s+0.37" % n, None]) testcases += [\ ["(0.1+1j)", None], ["(-0.1+1j)", None], ["(0.1-1j)", None], ["(-0.1-1j)", None], ["10j", None], ["-10j", None], ["100j", None], ["10000j", None], ["-10000000j", None], ["(10**100)*j", None], ["125+(10**100)*j", None], ["-125+(10**100)*j", None], ["(10**10)*(1+j)", None], ["(10**10)*(-1+j)", None], ["(10**100)*(1+j)", None], ["(10**100)*(-1+j)", None], ["(1.5-1j)", None], ["(6+4j)", None], ["(4+1j)", None], ["(3.5+2j)", None], ["(1.5-1j)", None], ["(-6-4j)", None], ["(-2-3j)", None], ["(-2.5-2j)", None], ["(4+1j)", None], ["(3+3j)", None], ["(2-2j)", None], ["1", "0"], ["2", "0"], ["3", "log(2)"], ["4", "log(6)"], ["5", "log(24)"], ["0.5", "log(pi)/2"], ["1.5", "log(sqrt(pi)/2)"], ["2.5", "log(3*sqrt(pi)/4)"], ["mpf('0.37')", None], ["0.25", "log(sqrt(2*sqrt(2*pi**3)/agm(1,sqrt(2))))"], ["-0.4", None], ["mpf('-1.9')", None], ["mpf('12.8')", None], ["mpf('33.7')", None], ["mpf('95.2')", None], ["mpf('160.3')", None], ["mpf('2057.8')", None], ["25", "log(ifac(24))"], ["80", "log(ifac(79))"], ["500", "log(ifac(500-1))"], ["8000", "log(ifac(8000-1))"], ["8000.5", None], ["mpf('8000.1')", None], ["mpf('1.37e10')", None], ["mpf('1.37e10')*(1+j)", None], ["mpf('1.37e10')*(-1+j)", None], ["mpf('1.37e10')*(-1-j)", None], ["mpf('1.37e10')*(-1+j)", None], ["mpf('1.37e100')", None], ["mpf('1.37e100')*(1+j)", None], ["mpf('1.37e100')*(-1+j)", None], ["mpf('1.37e100')*(-1-j)", None], ["mpf('1.37e100')*(-1+j)", None], ["3+4j", "mpc('" "-1.7566267846037841105306041816232757851567066070613445016197619371316057169" "4723618263960834804618463052988607348289672535780644470689771115236512106002" "5970873471563240537307638968509556191696167970488390423963867031934333890838" "8009531786948197210025029725361069435208930363494971027388382086721660805397" "9163230643216054580167976201709951509519218635460317367338612500626714783631" "7498317478048447525674016344322545858832610325861086336204591943822302971823" "5161814175530618223688296232894588415495615809337292518431903058265147109853" "1710568942184987827643886816200452860853873815413367529829631430146227470517" "6579967222200868632179482214312673161276976117132204633283806161971389519137" "1243359764435612951384238091232760634271570950240717650166551484551654327989" "9360285030081716934130446150245110557038117075172576825490035434069388648124" "6678152254554001586736120762641422590778766100376515737713938521275749049949" "1284143906816424244705094759339932733567910991920631339597278805393743140853" "391550313363278558195609260225928','" "4.74266443803465792819488940755002274088830335171164611359052405215840070271" "5906813009373171139767051863542508136875688550817670379002790304870822775498" "2809996675877564504192565392367259119610438951593128982646945990372179860613" "4294436498090428077839141927485901735557543641049637962003652638924845391650" "9546290137755550107224907606529385248390667634297183361902055842228798984200" "9591180450211798341715874477629099687609819466457990642030707080894518168924" "6805549314043258530272479246115112769957368212585759640878745385160943755234" "9398036774908108204370323896757543121853650025529763655312360354244898913463" "7115955702828838923393113618205074162812089732064414530813087483533203244056" "0546577484241423134079056537777170351934430586103623577814746004431994179990" "5318522939077992613855205801498201930221975721246498720895122345420698451980" "0051215797310305885845964334761831751370672996984756815410977750799748813563" "8784405288158432214886648743541773208808731479748217023665577802702269468013" "673719173759245720489020315779001')"], ] for z in [4, 14, 34, 64]: testcases.append(["(2+j)*%s/3" % z, None]) testcases.append(["(-2+j)*%s/3" % z, None]) testcases.append(["(1+2*j)*%s/3" % z, None]) testcases.append(["(2-j)*%s/3" % z, None]) testcases.append(["(20+j)*%s/3" % z, None]) testcases.append(["(-20+j)*%s/3" % z, None]) testcases.append(["(1+20*j)*%s/3" % z, None]) testcases.append(["(20-j)*%s/3" % z, None]) testcases.append(["(200+j)*%s/3" % z, None]) testcases.append(["(-200+j)*%s/3" % z, None]) testcases.append(["(1+200*j)*%s/3" % z, None]) testcases.append(["(200-j)*%s/3" % z, None]) # Poles for n in [0,1,2,3,4,25,-1,-2,-3,-4,-20,-21,-50,-51,-200,-201,-20000,-20001]: for t in ['1e-5', '1e-20', '1e-100', '1e-10000']: testcases.append(["fadd(%s,'%s',exact=True)" % (n, t), None]) testcases.append(["fsub(%s,'%s',exact=True)" % (n, t), None]) testcases.append(["fadd(%s,'%sj',exact=True)" % (n, t), None]) testcases.append(["fsub(%s,'%sj',exact=True)" % (n, t), None]) if __name__ == "__main__": from timeit import default_timer as clock tot_time = 0.0 for case in testcases: t1 = clock() testcase(case) t2 = clock() print("Test time:", t2-t1) print() tot_time += (t2-t1) print("Total time:", tot_time) print("Errors:", errcount)
7,228
32.467593
112
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_interval.py
from mpmath import * def test_interval_identity(): iv.dps = 15 assert mpi(2) == mpi(2, 2) assert mpi(2) != mpi(-2, 2) assert not (mpi(2) != mpi(2, 2)) assert mpi(-1, 1) == mpi(-1, 1) assert str(mpi('0.1')) == "[0.099999999999999991673, 0.10000000000000000555]" assert repr(mpi('0.1')) == "mpi('0.099999999999999992', '0.10000000000000001')" u = mpi(-1, 3) assert -1 in u assert 2 in u assert 3 in u assert -1.1 not in u assert 3.1 not in u assert mpi(-1, 3) in u assert mpi(0, 1) in u assert mpi(-1.1, 2) not in u assert mpi(2.5, 3.1) not in u w = mpi(-inf, inf) assert mpi(-5, 5) in w assert mpi(2, inf) in w assert mpi(0, 2) in mpi(0, 10) assert not (3 in mpi(-inf, 0)) def test_interval_hash(): assert hash(mpi(3)) == hash(3) assert hash(mpi(3.25)) == hash(3.25) assert hash(mpi(3,4)) == hash(mpi(3,4)) assert hash(iv.mpc(3)) == hash(3) assert hash(iv.mpc(3,4)) == hash(3+4j) assert hash(iv.mpc((1,3),(2,4))) == hash(iv.mpc((1,3),(2,4))) def test_interval_arithmetic(): iv.dps = 15 assert mpi(2) + mpi(3,4) == mpi(5,6) assert mpi(1, 2)**2 == mpi(1, 4) assert mpi(1) + mpi(0, 1e-50) == mpi(1, mpf('1.0000000000000002')) x = 1 / (1 / mpi(3)) assert x.a < 3 < x.b x = mpi(2) ** mpi(0.5) iv.dps += 5 sq = iv.sqrt(2) iv.dps -= 5 assert x.a < sq < x.b assert mpi(1) / mpi(1, inf) assert mpi(2, 3) / inf == mpi(0, 0) assert mpi(0) / inf == 0 assert mpi(0) / 0 == mpi(-inf, inf) assert mpi(inf) / 0 == mpi(-inf, inf) assert mpi(0) * inf == mpi(-inf, inf) assert 1 / mpi(2, inf) == mpi(0, 0.5) assert str((mpi(50, 50) * mpi(-10, -10)) / 3) == \ '[-166.66666666666668561, -166.66666666666665719]' assert mpi(0, 4) ** 3 == mpi(0, 64) assert mpi(2,4).mid == 3 iv.dps = 30 a = mpi(iv.pi) iv.dps = 15 b = +a assert b.a < a.a assert b.b > a.b a = mpi(iv.pi) assert a == +a assert abs(mpi(-1,2)) == mpi(0,2) assert abs(mpi(0.5,2)) == mpi(0.5,2) assert abs(mpi(-3,2)) == mpi(0,3) assert abs(mpi(-3,-0.5)) == mpi(0.5,3) assert mpi(0) * mpi(2,3) == mpi(0) assert mpi(2,3) * mpi(0) == mpi(0) assert mpi(1,3).delta == 2 assert mpi(1,2) - mpi(3,4) == mpi(-3,-1) assert mpi(-inf,0) - mpi(0,inf) == mpi(-inf,0) assert mpi(-inf,0) - mpi(-inf,inf) == mpi(-inf,inf) assert mpi(0,inf) - mpi(-inf,1) == mpi(-1,inf) def test_interval_mul(): assert mpi(-1, 0) * inf == mpi(-inf, 0) assert mpi(-1, 0) * -inf == mpi(0, inf) assert mpi(0, 1) * inf == mpi(0, inf) assert mpi(0, 1) * mpi(0, inf) == mpi(0, inf) assert mpi(-1, 1) * inf == mpi(-inf, inf) assert mpi(-1, 1) * mpi(0, inf) == mpi(-inf, inf) assert mpi(-1, 1) * mpi(-inf, inf) == mpi(-inf, inf) assert mpi(-inf, 0) * mpi(0, 1) == mpi(-inf, 0) assert mpi(-inf, 0) * mpi(0, 0) * mpi(-inf, 0) assert mpi(-inf, 0) * mpi(-inf, inf) == mpi(-inf, inf) assert mpi(-5,0)*mpi(-32,28) == mpi(-140,160) assert mpi(2,3) * mpi(-1,2) == mpi(-3,6) # Should be undefined? assert mpi(inf, inf) * 0 == mpi(-inf, inf) assert mpi(-inf, -inf) * 0 == mpi(-inf, inf) assert mpi(0) * mpi(-inf,2) == mpi(-inf,inf) assert mpi(0) * mpi(-2,inf) == mpi(-inf,inf) assert mpi(-2,inf) * mpi(0) == mpi(-inf,inf) assert mpi(-inf,2) * mpi(0) == mpi(-inf,inf) def test_interval_pow(): assert mpi(3)**2 == mpi(9, 9) assert mpi(-3)**2 == mpi(9, 9) assert mpi(-3, 1)**2 == mpi(0, 9) assert mpi(-3, -1)**2 == mpi(1, 9) assert mpi(-3, -1)**3 == mpi(-27, -1) assert mpi(-3, 1)**3 == mpi(-27, 1) assert mpi(-2, 3)**2 == mpi(0, 9) assert mpi(-3, 2)**2 == mpi(0, 9) assert mpi(4) ** -1 == mpi(0.25, 0.25) assert mpi(-4) ** -1 == mpi(-0.25, -0.25) assert mpi(4) ** -2 == mpi(0.0625, 0.0625) assert mpi(-4) ** -2 == mpi(0.0625, 0.0625) assert mpi(0, 1) ** inf == mpi(0, 1) assert mpi(0, 1) ** -inf == mpi(1, inf) assert mpi(0, inf) ** inf == mpi(0, inf) assert mpi(0, inf) ** -inf == mpi(0, inf) assert mpi(1, inf) ** inf == mpi(1, inf) assert mpi(1, inf) ** -inf == mpi(0, 1) assert mpi(2, 3) ** 1 == mpi(2, 3) assert mpi(2, 3) ** 0 == 1 assert mpi(1,3) ** mpi(2) == mpi(1,9) def test_interval_sqrt(): assert mpi(4) ** 0.5 == mpi(2) def test_interval_div(): assert mpi(0.5, 1) / mpi(-1, 0) == mpi(-inf, -0.5) assert mpi(0, 1) / mpi(0, 1) == mpi(0, inf) assert mpi(inf, inf) / mpi(inf, inf) == mpi(0, inf) assert mpi(inf, inf) / mpi(2, inf) == mpi(0, inf) assert mpi(inf, inf) / mpi(2, 2) == mpi(inf, inf) assert mpi(0, inf) / mpi(2, inf) == mpi(0, inf) assert mpi(0, inf) / mpi(2, 2) == mpi(0, inf) assert mpi(2, inf) / mpi(2, 2) == mpi(1, inf) assert mpi(2, inf) / mpi(2, inf) == mpi(0, inf) assert mpi(-4, 8) / mpi(1, inf) == mpi(-4, 8) assert mpi(-4, 8) / mpi(0.5, inf) == mpi(-8, 16) assert mpi(-inf, 8) / mpi(0.5, inf) == mpi(-inf, 16) assert mpi(-inf, inf) / mpi(0.5, inf) == mpi(-inf, inf) assert mpi(8, inf) / mpi(0.5, inf) == mpi(0, inf) assert mpi(-8, inf) / mpi(0.5, inf) == mpi(-16, inf) assert mpi(-4, 8) / mpi(inf, inf) == mpi(0, 0) assert mpi(0, 8) / mpi(inf, inf) == mpi(0, 0) assert mpi(0, 0) / mpi(inf, inf) == mpi(0, 0) assert mpi(-inf, 0) / mpi(inf, inf) == mpi(-inf, 0) assert mpi(-inf, 8) / mpi(inf, inf) == mpi(-inf, 0) assert mpi(-inf, inf) / mpi(inf, inf) == mpi(-inf, inf) assert mpi(-8, inf) / mpi(inf, inf) == mpi(0, inf) assert mpi(0, inf) / mpi(inf, inf) == mpi(0, inf) assert mpi(8, inf) / mpi(inf, inf) == mpi(0, inf) assert mpi(inf, inf) / mpi(inf, inf) == mpi(0, inf) assert mpi(-1, 2) / mpi(0, 1) == mpi(-inf, +inf) assert mpi(0, 1) / mpi(0, 1) == mpi(0.0, +inf) assert mpi(-1, 0) / mpi(0, 1) == mpi(-inf, 0.0) assert mpi(-0.5, -0.25) / mpi(0, 1) == mpi(-inf, -0.25) assert mpi(0.5, 1) / mpi(0, 1) == mpi(0.5, +inf) assert mpi(0.5, 4) / mpi(0, 1) == mpi(0.5, +inf) assert mpi(-1, -0.5) / mpi(0, 1) == mpi(-inf, -0.5) assert mpi(-4, -0.5) / mpi(0, 1) == mpi(-inf, -0.5) assert mpi(-1, 2) / mpi(-2, 0.5) == mpi(-inf, +inf) assert mpi(0, 1) / mpi(-2, 0.5) == mpi(-inf, +inf) assert mpi(-1, 0) / mpi(-2, 0.5) == mpi(-inf, +inf) assert mpi(-0.5, -0.25) / mpi(-2, 0.5) == mpi(-inf, +inf) assert mpi(0.5, 1) / mpi(-2, 0.5) == mpi(-inf, +inf) assert mpi(0.5, 4) / mpi(-2, 0.5) == mpi(-inf, +inf) assert mpi(-1, -0.5) / mpi(-2, 0.5) == mpi(-inf, +inf) assert mpi(-4, -0.5) / mpi(-2, 0.5) == mpi(-inf, +inf) assert mpi(-1, 2) / mpi(-1, 0) == mpi(-inf, +inf) assert mpi(0, 1) / mpi(-1, 0) == mpi(-inf, 0.0) assert mpi(-1, 0) / mpi(-1, 0) == mpi(0.0, +inf) assert mpi(-0.5, -0.25) / mpi(-1, 0) == mpi(0.25, +inf) assert mpi(0.5, 1) / mpi(-1, 0) == mpi(-inf, -0.5) assert mpi(0.5, 4) / mpi(-1, 0) == mpi(-inf, -0.5) assert mpi(-1, -0.5) / mpi(-1, 0) == mpi(0.5, +inf) assert mpi(-4, -0.5) / mpi(-1, 0) == mpi(0.5, +inf) assert mpi(-1, 2) / mpi(0.5, 1) == mpi(-2.0, 4.0) assert mpi(0, 1) / mpi(0.5, 1) == mpi(0.0, 2.0) assert mpi(-1, 0) / mpi(0.5, 1) == mpi(-2.0, 0.0) assert mpi(-0.5, -0.25) / mpi(0.5, 1) == mpi(-1.0, -0.25) assert mpi(0.5, 1) / mpi(0.5, 1) == mpi(0.5, 2.0) assert mpi(0.5, 4) / mpi(0.5, 1) == mpi(0.5, 8.0) assert mpi(-1, -0.5) / mpi(0.5, 1) == mpi(-2.0, -0.5) assert mpi(-4, -0.5) / mpi(0.5, 1) == mpi(-8.0, -0.5) assert mpi(-1, 2) / mpi(-2, -0.5) == mpi(-4.0, 2.0) assert mpi(0, 1) / mpi(-2, -0.5) == mpi(-2.0, 0.0) assert mpi(-1, 0) / mpi(-2, -0.5) == mpi(0.0, 2.0) assert mpi(-0.5, -0.25) / mpi(-2, -0.5) == mpi(0.125, 1.0) assert mpi(0.5, 1) / mpi(-2, -0.5) == mpi(-2.0, -0.25) assert mpi(0.5, 4) / mpi(-2, -0.5) == mpi(-8.0, -0.25) assert mpi(-1, -0.5) / mpi(-2, -0.5) == mpi(0.25, 2.0) assert mpi(-4, -0.5) / mpi(-2, -0.5) == mpi(0.25, 8.0) # Should be undefined? assert mpi(0, 0) / mpi(0, 0) == mpi(-inf, inf) assert mpi(0, 0) / mpi(0, 1) == mpi(-inf, inf) def test_interval_cos_sin(): iv.dps = 15 cos = iv.cos sin = iv.sin tan = iv.tan pi = iv.pi # Around 0 assert cos(mpi(0)) == 1 assert sin(mpi(0)) == 0 assert cos(mpi(0,1)) == mpi(0.54030230586813965399, 1.0) assert sin(mpi(0,1)) == mpi(0, 0.8414709848078966159) assert cos(mpi(1,2)) == mpi(-0.4161468365471424069, 0.54030230586813976501) assert sin(mpi(1,2)) == mpi(0.84147098480789650488, 1.0) assert sin(mpi(1,2.5)) == mpi(0.59847214410395643824, 1.0) assert cos(mpi(-1, 1)) == mpi(0.54030230586813965399, 1.0) assert cos(mpi(-1, 0.5)) == mpi(0.54030230586813965399, 1.0) assert cos(mpi(-1, 1.5)) == mpi(0.070737201667702906405, 1.0) assert sin(mpi(-1,1)) == mpi(-0.8414709848078966159, 0.8414709848078966159) assert sin(mpi(-1,0.5)) == mpi(-0.8414709848078966159, 0.47942553860420300538) assert mpi(-0.8414709848078966159, 1.00000000000000002e-100) in sin(mpi(-1,1e-100)) assert mpi(-2.00000000000000004e-100, 1.00000000000000002e-100) in sin(mpi(-2e-100,1e-100)) # Same interval assert cos(mpi(2, 2.5)) assert cos(mpi(3.5, 4)) == mpi(-0.93645668729079634129, -0.65364362086361182946) assert cos(mpi(5, 5.5)) == mpi(0.28366218546322624627, 0.70866977429126010168) assert mpi(0.59847214410395654927, 0.90929742682568170942) in sin(mpi(2, 2.5)) assert sin(mpi(3.5, 4)) == mpi(-0.75680249530792831347, -0.35078322768961983646) assert sin(mpi(5, 5.5)) == mpi(-0.95892427466313856499, -0.70554032557039181306) # Higher roots iv.dps = 55 w = 4*10**50 + mpi(0.5) for p in [15, 40, 80]: iv.dps = p assert 0 in sin(4*mpi(pi)) assert 0 in sin(4*10**50*mpi(pi)) assert 0 in cos((4+0.5)*mpi(pi)) assert 0 in cos(w*mpi(pi)) assert 1 in cos(4*mpi(pi)) assert 1 in cos(4*10**50*mpi(pi)) iv.dps = 15 assert cos(mpi(2,inf)) == mpi(-1,1) assert sin(mpi(2,inf)) == mpi(-1,1) assert cos(mpi(-inf,2)) == mpi(-1,1) assert sin(mpi(-inf,2)) == mpi(-1,1) u = tan(mpi(0.5,1)) assert mpf(u.a).ae(mp.tan(0.5)) assert mpf(u.b).ae(mp.tan(1)) v = iv.cot(mpi(0.5,1)) assert mpf(v.a).ae(mp.cot(1)) assert mpf(v.b).ae(mp.cot(0.5)) # Sanity check of evaluation at n*pi and (n+1/2)*pi for n in range(-5,7,2): x = iv.cos(n*iv.pi) assert -1 in x assert x >= -1 assert x != -1 x = iv.sin((n+0.5)*iv.pi) assert -1 in x assert x >= -1 assert x != -1 for n in range(-6,8,2): x = iv.cos(n*iv.pi) assert 1 in x assert x <= 1 if n: assert x != 1 x = iv.sin((n+0.5)*iv.pi) assert 1 in x assert x <= 1 assert x != 1 for n in range(-6,7): x = iv.cos((n+0.5)*iv.pi) assert x.a < 0 < x.b x = iv.sin(n*iv.pi) if n: assert x.a < 0 < x.b def test_interval_complex(): # TODO: many more tests iv.dps = 15 mp.dps = 15 assert iv.mpc(2,3) == 2+3j assert iv.mpc(2,3) != 2+4j assert iv.mpc(2,3) != 1+3j assert 1+3j in iv.mpc([1,2],[3,4]) assert 2+5j not in iv.mpc([1,2],[3,4]) assert iv.mpc(1,2) + 1j == 1+3j assert iv.mpc([1,2],[2,3]) + 2+3j == iv.mpc([3,4],[5,6]) assert iv.mpc([2,4],[4,8]) / 2 == iv.mpc([1,2],[2,4]) assert iv.mpc([1,2],[2,4]) * 2j == iv.mpc([-8,-4],[2,4]) assert iv.mpc([2,4],[4,8]) / 2j == iv.mpc([2,4],[-2,-1]) assert iv.exp(2+3j).ae(mp.exp(2+3j)) assert iv.log(2+3j).ae(mp.log(2+3j)) assert (iv.mpc(2,3) ** iv.mpc(0.5,2)).ae(mp.mpc(2,3) ** mp.mpc(0.5,2)) assert 1j in (iv.mpf(-1) ** 0.5) assert 1j in (iv.mpc(-1) ** 0.5) assert abs(iv.mpc(0)) == 0 assert abs(iv.mpc(inf)) == inf assert abs(iv.mpc(3,4)) == 5 assert abs(iv.mpc(4)) == 4 assert abs(iv.mpc(0,4)) == 4 assert abs(iv.mpc(0,[2,3])) == iv.mpf([2,3]) assert abs(iv.mpc(0,[-3,2])) == iv.mpf([0,3]) assert abs(iv.mpc([3,5],[4,12])) == iv.mpf([5,13]) assert abs(iv.mpc([3,5],[-4,12])) == iv.mpf([3,13]) assert iv.mpc(2,3) ** 0 == 1 assert iv.mpc(2,3) ** 1 == (2+3j) assert iv.mpc(2,3) ** 2 == (2+3j)**2 assert iv.mpc(2,3) ** 3 == (2+3j)**3 assert iv.mpc(2,3) ** 4 == (2+3j)**4 assert iv.mpc(2,3) ** 5 == (2+3j)**5 assert iv.mpc(2,2) ** (-1) == (2+2j) ** (-1) assert iv.mpc(2,2) ** (-2) == (2+2j) ** (-2) assert iv.cos(2).ae(mp.cos(2)) assert iv.sin(2).ae(mp.sin(2)) assert iv.cos(2+3j).ae(mp.cos(2+3j)) assert iv.sin(2+3j).ae(mp.sin(2+3j)) def test_interval_complex_arg(): mp.dps = 15 iv.dps = 15 assert iv.arg(3) == 0 assert iv.arg(0) == 0 assert iv.arg([0,3]) == 0 assert iv.arg(-3).ae(pi) assert iv.arg(2+3j).ae(iv.arg(2+3j)) z = iv.mpc([-2,-1],[3,4]) t = iv.arg(z) assert t.a.ae(mp.arg(-1+4j)) assert t.b.ae(mp.arg(-2+3j)) z = iv.mpc([-2,1],[3,4]) t = iv.arg(z) assert t.a.ae(mp.arg(1+3j)) assert t.b.ae(mp.arg(-2+3j)) z = iv.mpc([1,2],[3,4]) t = iv.arg(z) assert t.a.ae(mp.arg(2+3j)) assert t.b.ae(mp.arg(1+4j)) z = iv.mpc([1,2],[-2,3]) t = iv.arg(z) assert t.a.ae(mp.arg(1-2j)) assert t.b.ae(mp.arg(1+3j)) z = iv.mpc([1,2],[-4,-3]) t = iv.arg(z) assert t.a.ae(mp.arg(1-4j)) assert t.b.ae(mp.arg(2-3j)) z = iv.mpc([-1,2],[-4,-3]) t = iv.arg(z) assert t.a.ae(mp.arg(-1-3j)) assert t.b.ae(mp.arg(2-3j)) z = iv.mpc([-2,-1],[-4,-3]) t = iv.arg(z) assert t.a.ae(mp.arg(-2-3j)) assert t.b.ae(mp.arg(-1-4j)) z = iv.mpc([-2,-1],[-3,3]) t = iv.arg(z) assert t.a.ae(-mp.pi) assert t.b.ae(mp.pi) z = iv.mpc([-2,2],[-3,3]) t = iv.arg(z) assert t.a.ae(-mp.pi) assert t.b.ae(mp.pi) def test_interval_ae(): iv.dps = 15 x = iv.mpf([1,2]) assert x.ae(1) is None assert x.ae(1.5) is None assert x.ae(2) is None assert x.ae(2.01) is False assert x.ae(0.99) is False x = iv.mpf(3.5) assert x.ae(3.5) is True assert x.ae(3.5+1e-15) is True assert x.ae(3.5-1e-15) is True assert x.ae(3.501) is False assert x.ae(3.499) is False assert x.ae(iv.mpf([3.5,3.501])) is None assert x.ae(iv.mpf([3.5,4.5+1e-15])) is None def test_interval_nstr(): iv.dps = n = 30 x = mpi(1, 2) # FIXME: error_dps should not be necessary assert iv.nstr(x, n, mode='plusminus', error_dps=6) == '1.5 +- 0.5' assert iv.nstr(x, n, mode='plusminus', use_spaces=False, error_dps=6) == '1.5+-0.5' assert iv.nstr(x, n, mode='percent') == '1.5 (33.33%)' assert iv.nstr(x, n, mode='brackets', use_spaces=False) == '[1.0,2.0]' assert iv.nstr(x, n, mode='brackets' , brackets=('<', '>')) == '<1.0, 2.0>' x = mpi('5.2582327113062393041', '5.2582327113062749951') assert iv.nstr(x, n, mode='diff') == '5.2582327113062[393041, 749951]' assert iv.nstr(iv.cos(mpi(1)), n, mode='diff', use_spaces=False) == '0.54030230586813971740093660744[2955,3053]' assert iv.nstr(mpi('1e123', '1e129'), n, mode='diff') == '[1.0e+123, 1.0e+129]' exp = iv.exp assert iv.nstr(iv.exp(mpi('5000.1')), n, mode='diff') == '3.2797365856787867069110487[0926, 1191]e+2171' iv.dps = 15 def test_mpi_from_str(): iv.dps = 15 assert iv.convert('1.5 +- 0.5') == mpi(mpf('1.0'), mpf('2.0')) assert mpi(1, 2) in iv.convert('1.5 (33.33333333333333333333333333333%)') assert iv.convert('[1, 2]') == mpi(1, 2) assert iv.convert('1[2, 3]') == mpi(12, 13) assert iv.convert('1.[23,46]e-8') == mpi('1.23e-8', '1.46e-8') assert iv.convert('12[3.4,5.9]e4') == mpi('123.4e+4', '125.9e4') def test_interval_gamma(): mp.dps = 15 iv.dps = 15 # TODO: need many more tests assert iv.rgamma(0) == 0 assert iv.fac(0) == 1 assert iv.fac(1) == 1 assert iv.fac(2) == 2 assert iv.fac(3) == 6 assert iv.gamma(0) == [-inf,inf] assert iv.gamma(1) == 1 assert iv.gamma(2) == 1 assert iv.gamma(3) == 2 assert -3.5449077018110320546 in iv.gamma(-0.5) assert iv.loggamma(1) == 0 assert iv.loggamma(2) == 0 assert 0.69314718055994530942 in iv.loggamma(3) # Test tight log-gamma endpoints based on monotonicity xs = [iv.mpc([2,3],[1,4]), iv.mpc([2,3],[-4,-1]), iv.mpc([2,3],[-1,4]), iv.mpc([2,3],[-4,1]), iv.mpc([2,3],[-4,4]), iv.mpc([-3,-2],[2,4]), iv.mpc([-3,-2],[-4,-2])] for x in xs: ys = [mp.loggamma(mp.mpc(x.a,x.c)), mp.loggamma(mp.mpc(x.b,x.c)), mp.loggamma(mp.mpc(x.a,x.d)), mp.loggamma(mp.mpc(x.b,x.d))] if 0 in x.imag: ys += [mp.loggamma(x.a), mp.loggamma(x.b)] min_real = min([y.real for y in ys]) max_real = max([y.real for y in ys]) min_imag = min([y.imag for y in ys]) max_imag = max([y.imag for y in ys]) z = iv.loggamma(x) assert z.a.ae(min_real) assert z.b.ae(max_real) assert z.c.ae(min_imag) assert z.d.ae(max_imag)
17,133
37.764706
116
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_calculus.py
from mpmath import * def test_approximation(): mp.dps = 15 f = lambda x: cos(2-2*x)/x p, err = chebyfit(f, [2, 4], 8, error=True) assert err < 1e-5 for i in range(10): x = 2 + i/5. assert abs(polyval(p, x) - f(x)) < err def test_limits(): mp.dps = 15 assert limit(lambda x: (x-sin(x))/x**3, 0).ae(mpf(1)/6) assert limit(lambda n: (1+1/n)**n, inf).ae(e) def test_polyval(): assert polyval([], 3) == 0 assert polyval([0], 3) == 0 assert polyval([5], 3) == 5 # 4x^3 - 2x + 5 p = [4, 0, -2, 5] assert polyval(p,4) == 253 assert polyval(p,4,derivative=True) == (253, 190) def test_polyroots(): p = polyroots([1,-4]) assert p[0].ae(4) p, q = polyroots([1,2,3]) assert p.ae(-1 - sqrt(2)*j) assert q.ae(-1 + sqrt(2)*j) #this is not a real test, it only tests a specific case assert polyroots([1]) == [] try: polyroots([0]) assert False except ValueError: pass def test_polyroots_legendre(): n = 64 coeffs = [11975573020964041433067793888190275875, 0, -190100434726484311252477736051902332000, 0, 1437919688271127330313741595496589239248, 0, -6897338342113537600691931230430793911840, 0, 23556405536185284408974715545252277554280, 0, -60969520211303089058522793175947071316960, 0, 124284021969194758465450309166353645376880, 0, -204721258548015217049921875719981284186016, 0, 277415422258095841688223780704620656114900, 0, -313237834141273382807123548182995095192800, 0, 297432255354328395601259515935229287637200, 0, -239057700565161140389797367947941296605600, 0, 163356095386193445933028201431093219347160, 0, -95158890516229191805647495979277603503200, 0, 47310254620162038075933656063247634556400, 0, -20071017111583894941305187420771723751200, 0, 7255051932731034189479516844750603752850, 0, -2228176940331017311443863996901733412640, 0, 579006552594977616773047095969088431600, 0, -126584428502545713788439446082310831200, 0, 23112325428835593809686977515028663000, 0, -3491517141958743235617737161547844000, 0, 431305058712550634988073414073557200, 0, -42927166660756742088912492757452000, 0, 3378527005707706553294038781836500, 0, -205277590220215081719131470288800, 0, 9330799555464321896324157740400, 0, -304114948474392713657972548576, 0, 6695289961520387531608984680, 0, -91048139350447232095702560, 0, 659769125727878493447120, 0, -1905929106580294155360, 0, 916312070471295267] with mp.workdps(3): try: roots = polyroots(coeffs, maxsteps=5, cleanup=True, error=False, extraprec=n*10) raise AssertionError("polyroots() didn't raise NoConvergence") except (mp.NoConvergence): pass roots = polyroots(coeffs, maxsteps=50, cleanup=True, error=False, extraprec=n*10) roots = [str(r) for r in roots] assert roots == \ ['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961', '-0.946', '-0.93', '-0.911', '-0.889', '-0.866', '-0.841', '-0.813', '-0.784', '-0.753', '-0.72', '-0.685', '-0.649', '-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402', '-0.357', '-0.311', '-0.265', '-0.217', '-0.17', '-0.121', '-0.073', '-0.0243', '0.0243', '0.073', '0.121', '0.17', '0.217', '0.265', '0.311', '0.357', '0.402', '0.446', '0.489', '0.531', '0.572', '0.611', '0.649', '0.685', '0.72', '0.753', '0.784', '0.813', '0.841', '0.866', '0.889', '0.911', '0.93', '0.946', '0.961', '0.973', '0.983', '0.991', '0.996', '0.999'] def test_polyroots_legendre_init(): extra_prec = 100 coeffs = [11975573020964041433067793888190275875, 0, -190100434726484311252477736051902332000, 0, 1437919688271127330313741595496589239248, 0, -6897338342113537600691931230430793911840, 0, 23556405536185284408974715545252277554280, 0, -60969520211303089058522793175947071316960, 0, 124284021969194758465450309166353645376880, 0, -204721258548015217049921875719981284186016, 0, 277415422258095841688223780704620656114900, 0, -313237834141273382807123548182995095192800, 0, 297432255354328395601259515935229287637200, 0, -239057700565161140389797367947941296605600, 0, 163356095386193445933028201431093219347160, 0, -95158890516229191805647495979277603503200, 0, 47310254620162038075933656063247634556400, 0, -20071017111583894941305187420771723751200, 0, 7255051932731034189479516844750603752850, 0, -2228176940331017311443863996901733412640, 0, 579006552594977616773047095969088431600, 0, -126584428502545713788439446082310831200, 0, 23112325428835593809686977515028663000, 0, -3491517141958743235617737161547844000, 0, 431305058712550634988073414073557200, 0, -42927166660756742088912492757452000, 0, 3378527005707706553294038781836500, 0, -205277590220215081719131470288800, 0, 9330799555464321896324157740400, 0, -304114948474392713657972548576, 0, 6695289961520387531608984680, 0, -91048139350447232095702560, 0, 659769125727878493447120, 0, -1905929106580294155360, 0, 916312070471295267] roots_init = matrix(['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961', '-0.946', '-0.93', '-0.911', '-0.889', '-0.866', '-0.841', '-0.813', '-0.784', '-0.753', '-0.72', '-0.685', '-0.649', '-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402', '-0.357', '-0.311', '-0.265', '-0.217', '-0.17', '-0.121', '-0.073', '-0.0243', '0.0243', '0.073', '0.121', '0.17', '0.217', '0.265', ' 0.311', '0.357', '0.402', '0.446', '0.489', '0.531', '0.572', '0.611', '0.649', '0.685', '0.72', '0.753', '0.784', '0.813', '0.841', '0.866', '0.889', '0.911', '0.93', '0.946', '0.961', '0.973', '0.983', '0.991', '0.996', '0.999', '1.0']) with mp.workdps(2*mp.dps): roots_exact = polyroots(coeffs, maxsteps=50, cleanup=True, error=False, extraprec=2*extra_prec) try: roots = polyroots(coeffs, maxsteps=5, cleanup=True, error=False, extraprec=extra_prec) raise AssertionError("polyroots() didn't raise NoConvergence") except (mp.NoConvergence): pass roots,err = polyroots(coeffs, maxsteps=5, cleanup=True, error=True, extraprec=extra_prec,roots_init=roots_init) assert max(matrix(roots_exact)-matrix(roots).apply(abs)) < err roots1,err1 = polyroots(coeffs, maxsteps=25, cleanup=True, error=True, extraprec=extra_prec,roots_init=roots_init[:60]) assert max(matrix(roots_exact)-matrix(roots1).apply(abs)) < err1 def test_pade(): one = mpf(1) mp.dps = 20 N = 10 a = [one] k = 1 for i in range(1, N+1): k *= i a.append(one/k) p, q = pade(a, N//2, N//2) for x in arange(0, 1, 0.1): r = polyval(p[::-1], x)/polyval(q[::-1], x) assert(r.ae(exp(x), 1.0e-10)) mp.dps = 15 def test_fourier(): mp.dps = 15 c, s = fourier(lambda x: x+1, [-1, 2], 2) #plot([lambda x: x+1, lambda x: fourierval((c, s), [-1, 2], x)], [-1, 2]) assert c[0].ae(1.5) assert c[1].ae(-3*sqrt(3)/(2*pi)) assert c[2].ae(3*sqrt(3)/(4*pi)) assert s[0] == 0 assert s[1].ae(3/(2*pi)) assert s[2].ae(3/(4*pi)) assert fourierval((c, s), [-1, 2], 1).ae(1.9134966715663442) def test_differint(): mp.dps = 15 assert differint(lambda t: t, 2, -0.5).ae(8*sqrt(2/pi)/3) def test_invlap(): mp.dps = 15 t = 0.01 fp = lambda p: 1/(p+1)**2 ft = lambda t: t*exp(-t) ftt = ft(t) assert invertlaplace(fp,t,method='talbot').ae(ftt) assert invertlaplace(fp,t,method='stehfest').ae(ftt) assert invertlaplace(fp,t,method='dehoog').ae(ftt) t = 1.0 ftt = ft(t) assert invertlaplace(fp,t,method='talbot').ae(ftt) assert invertlaplace(fp,t,method='stehfest').ae(ftt) assert invertlaplace(fp,t,method='dehoog').ae(ftt) t = 0.01 fp = lambda p: log(p)/p ft = lambda t: -euler-log(t) ftt = ft(t) assert invertlaplace(fp,t,method='talbot').ae(ftt) assert invertlaplace(fp,t,method='stehfest').ae(ftt) assert invertlaplace(fp,t,method='dehoog').ae(ftt) t = 1.0 ftt = ft(t) assert invertlaplace(fp,t,method='talbot').ae(ftt) assert invertlaplace(fp,t,method='stehfest').ae(ftt) assert invertlaplace(fp,t,method='dehoog').ae(ftt)
9,194
40.418919
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/extratest_bessel.py
# Extra stress testing for Bessel functions # Reference zeros generated with the aid of scipy.special # jn_zero, jnp_zero, yn_zero, ynp_zero from mpmath import * V = 15 M = 15 jn_small_zeros = \ [[2.4048255576957728, 5.5200781102863106, 8.6537279129110122, 11.791534439014282, 14.930917708487786, 18.071063967910923, 21.211636629879259, 24.352471530749303, 27.493479132040255, 30.634606468431975, 33.775820213573569, 36.917098353664044, 40.058425764628239, 43.19979171317673, 46.341188371661814], [3.8317059702075123, 7.0155866698156188, 10.173468135062722, 13.323691936314223, 16.470630050877633, 19.615858510468242, 22.760084380592772, 25.903672087618383, 29.046828534916855, 32.189679910974404, 35.332307550083865, 38.474766234771615, 41.617094212814451, 44.759318997652822, 47.901460887185447], [5.1356223018406826, 8.4172441403998649, 11.619841172149059, 14.795951782351261, 17.959819494987826, 21.116997053021846, 24.270112313573103, 27.420573549984557, 30.569204495516397, 33.7165195092227, 36.86285651128381, 40.008446733478192, 43.153453778371463, 46.297996677236919, 49.442164110416873], [6.3801618959239835, 9.7610231299816697, 13.015200721698434, 16.223466160318768, 19.409415226435012, 22.582729593104442, 25.748166699294978, 28.908350780921758, 32.064852407097709, 35.218670738610115, 38.370472434756944, 41.520719670406776, 44.669743116617253, 47.817785691533302, 50.965029906205183], [7.5883424345038044, 11.064709488501185, 14.37253667161759, 17.615966049804833, 20.826932956962388, 24.01901952477111, 27.199087765981251, 30.371007667117247, 33.537137711819223, 36.699001128744649, 39.857627302180889, 43.01373772335443, 46.167853512924375, 49.320360686390272, 52.471551398458023], [8.771483815959954, 12.338604197466944, 15.700174079711671, 18.980133875179921, 22.217799896561268, 25.430341154222704, 28.626618307291138, 31.811716724047763, 34.988781294559295, 38.159868561967132, 41.326383254047406, 44.489319123219673, 47.649399806697054, 50.80716520300633, 53.963026558378149], [9.9361095242176849, 13.589290170541217, 17.003819667816014, 20.320789213566506, 23.58608443558139, 26.820151983411405, 30.033722386570469, 33.233041762847123, 36.422019668258457, 39.603239416075404, 42.778481613199507, 45.949015998042603, 49.11577372476426, 52.279453903601052, 55.440592068853149], [11.086370019245084, 14.821268727013171, 18.287582832481726, 21.641541019848401, 24.934927887673022, 28.191188459483199, 31.42279419226558, 34.637089352069324, 37.838717382853611, 41.030773691585537, 44.21540850526126, 47.394165755570512, 50.568184679795566, 53.738325371963291, 56.905249991978781], [12.225092264004655, 16.037774190887709, 19.554536430997055, 22.94517313187462, 26.266814641176644, 29.54565967099855, 32.795800037341462, 36.025615063869571, 39.240447995178135, 42.443887743273558, 45.638444182199141, 48.825930381553857, 52.007691456686903, 55.184747939289049, 58.357889025269694], [13.354300477435331, 17.241220382489128, 20.807047789264107, 24.233885257750552, 27.583748963573006, 30.885378967696675, 34.154377923855096, 37.400099977156589, 40.628553718964528, 43.843801420337347, 47.048700737654032, 50.245326955305383, 53.435227157042058, 56.619580266508436, 59.799301630960228], [14.475500686554541, 18.433463666966583, 22.046985364697802, 25.509450554182826, 28.887375063530457, 32.211856199712731, 35.499909205373851, 38.761807017881651, 42.004190236671805, 45.231574103535045, 48.447151387269394, 51.653251668165858, 54.851619075963349, 58.043587928232478, 61.230197977292681], [15.589847884455485, 19.61596690396692, 23.275853726263409, 26.773322545509539, 30.17906117878486, 33.526364075588624, 36.833571341894905, 40.111823270954241, 43.368360947521711, 46.608132676274944, 49.834653510396724, 53.050498959135054, 56.257604715114484, 59.457456908388002, 62.651217388202912], [16.698249933848246, 20.789906360078443, 24.494885043881354, 28.026709949973129, 31.45996003531804, 34.829986990290238, 38.156377504681354, 41.451092307939681, 44.721943543191147, 47.974293531269048, 51.211967004101068, 54.437776928325074, 57.653844811906946, 60.8618046824805, 64.062937824850136], [17.801435153282442, 21.95624406783631, 25.705103053924724, 29.270630441874802, 32.731053310978403, 36.123657666448762, 39.469206825243883, 42.780439265447158, 46.06571091157561, 49.330780096443524, 52.579769064383396, 55.815719876305778, 59.040934037249271, 62.257189393731728, 65.465883797232125], [18.899997953174024, 23.115778347252756, 26.907368976182104, 30.505950163896036, 33.993184984781542, 37.408185128639695, 40.772827853501868, 44.100590565798301, 47.400347780543231, 50.678236946479898, 53.93866620912693, 57.184898598119301, 60.419409852130297, 63.644117508962281, 66.860533012260103]] jnp_small_zeros = \ [[0.0, 3.8317059702075123, 7.0155866698156188, 10.173468135062722, 13.323691936314223, 16.470630050877633, 19.615858510468242, 22.760084380592772, 25.903672087618383, 29.046828534916855, 32.189679910974404, 35.332307550083865, 38.474766234771615, 41.617094212814451, 44.759318997652822], [1.8411837813406593, 5.3314427735250326, 8.5363163663462858, 11.706004902592064, 14.863588633909033, 18.015527862681804, 21.16436985918879, 24.311326857210776, 27.457050571059246, 30.601922972669094, 33.746182898667383, 36.889987409236811, 40.033444053350675, 43.176628965448822, 46.319597561173912], [3.0542369282271403, 6.7061331941584591, 9.9694678230875958, 13.170370856016123, 16.347522318321783, 19.512912782488205, 22.671581772477426, 25.826037141785263, 28.977672772993679, 32.127327020443474, 35.275535050674691, 38.422654817555906, 41.568934936074314, 44.714553532819734, 47.859641607992093], [4.2011889412105285, 8.0152365983759522, 11.345924310743006, 14.585848286167028, 17.78874786606647, 20.9724769365377, 24.144897432909265, 27.310057930204349, 30.470268806290424, 33.626949182796679, 36.781020675464386, 39.933108623659488, 43.083652662375079, 46.232971081836478, 49.381300092370349], [5.3175531260839944, 9.2823962852416123, 12.681908442638891, 15.964107037731551, 19.196028800048905, 22.401032267689004, 25.589759681386733, 28.767836217666503, 31.938539340972783, 35.103916677346764, 38.265316987088158, 41.423666498500732, 44.579623137359257, 47.733667523865744, 50.886159153182682], [6.4156163757002403, 10.519860873772308, 13.9871886301403, 17.312842487884625, 20.575514521386888, 23.803581476593863, 27.01030789777772, 30.20284907898166, 33.385443901010121, 36.560777686880356, 39.730640230067416, 42.896273163494417, 46.058566273567043, 49.218174614666636, 52.375591529563596], [7.501266144684147, 11.734935953042708, 15.268181461097873, 18.637443009666202, 21.931715017802236, 25.183925599499626, 28.409776362510085, 31.617875716105035, 34.81339298429743, 37.999640897715301, 41.178849474321413, 44.352579199070217, 47.521956905768113, 50.687817781723741, 53.85079463676896], [8.5778364897140741, 12.932386237089576, 16.529365884366944, 19.941853366527342, 23.268052926457571, 26.545032061823576, 29.790748583196614, 33.015178641375142, 36.224380548787162, 39.422274578939259, 42.611522172286684, 45.793999658055002, 48.971070951900596, 52.143752969301988, 55.312820330403446], [9.6474216519972168, 14.115518907894618, 17.774012366915256, 21.229062622853124, 24.587197486317681, 27.889269427955092, 31.155326556188325, 34.39662855427218, 37.620078044197086, 40.830178681822041, 44.030010337966153, 47.221758471887113, 50.407020967034367, 53.586995435398319, 56.762598475105272], [10.711433970699945, 15.28673766733295, 19.004593537946053, 22.501398726777283, 25.891277276839136, 29.218563499936081, 32.505247352375523, 35.763792928808799, 39.001902811514218, 42.224638430753279, 45.435483097475542, 48.636922645305525, 51.830783925834728, 55.01844255063594, 58.200955824859509], [11.770876674955582, 16.447852748486498, 20.223031412681701, 23.760715860327448, 27.182021527190532, 30.534504754007074, 33.841965775135715, 37.118000423665604, 40.371068905333891, 43.606764901379516, 46.828959446564562, 50.040428970943456, 53.243223214220535, 56.438892058982552, 59.628631306921512], [12.826491228033465, 17.600266557468326, 21.430854238060294, 25.008518704644261, 28.460857279654847, 31.838424458616998, 35.166714427392629, 38.460388720328256, 41.728625562624312, 44.977526250903469, 48.211333836373288, 51.433105171422278, 54.645106240447105, 57.849056857839799, 61.046288512821078], [13.878843069697276, 18.745090916814406, 22.629300302835503, 26.246047773946584, 29.72897816891134, 33.131449953571661, 36.480548302231658, 39.791940718940855, 43.075486800191012, 46.337772104541405, 49.583396417633095, 52.815686826850452, 56.037118687012179, 59.249577075517968, 62.454525995970462], [14.928374492964716, 19.88322436109951, 23.81938909003628, 27.474339750968247, 30.987394331665278, 34.414545662167183, 37.784378506209499, 41.113512376883377, 44.412454519229281, 47.688252845993366, 50.945849245830813, 54.188831071035124, 57.419876154678179, 60.641030026538746, 63.853885828967512], [15.975438807484321, 21.015404934568315, 25.001971500138194, 28.694271223110755, 32.236969407878118, 35.688544091185301, 39.078998185245057, 42.425854432866141, 45.740236776624833, 49.029635055514276, 52.299319390331728, 55.553127779547459, 58.793933759028134, 62.02393848337554, 65.244860767043859]] yn_small_zeros = \ [[0.89357696627916752, 3.9576784193148579, 7.0860510603017727, 10.222345043496417, 13.361097473872763, 16.500922441528091, 19.64130970088794, 22.782028047291559, 25.922957653180923, 29.064030252728398, 32.205204116493281, 35.346452305214321, 38.487756653081537, 41.629104466213808, 44.770486607221993], [2.197141326031017, 5.4296810407941351, 8.5960058683311689, 11.749154830839881, 14.897442128336725, 18.043402276727856, 21.188068934142213, 24.331942571356912, 27.475294980449224, 30.618286491641115, 33.761017796109326, 36.90355531614295, 40.045944640266876, 43.188218097393211, 46.330399250701687], [3.3842417671495935, 6.7938075132682675, 10.023477979360038, 13.209986710206416, 16.378966558947457, 19.539039990286384, 22.69395593890929, 25.845613720902269, 28.995080395650151, 32.143002257627551, 35.289793869635804, 38.435733485446343, 41.581014867297885, 44.725777117640461, 47.870122696676504], [4.5270246611496439, 8.0975537628604907, 11.396466739595867, 14.623077742393873, 17.81845523294552, 20.997284754187761, 24.166235758581828, 27.328799850405162, 30.486989604098659, 33.642049384702463, 36.794791029185579, 39.945767226378749, 43.095367507846703, 46.2438744334407, 49.391498015725107], [5.6451478942208959, 9.3616206152445429, 12.730144474090465, 15.999627085382479, 19.22442895931681, 22.424810599698521, 25.610267054939328, 28.785893657666548, 31.954686680031668, 35.118529525584828, 38.278668089521758, 41.435960629910073, 44.591018225353424, 47.744288086361052, 50.896105199722123], [6.7471838248710219, 10.597176726782031, 14.033804104911233, 17.347086393228382, 20.602899017175335, 23.826536030287532, 27.030134937138834, 30.220335654231385, 33.401105611047908, 36.574972486670962, 39.743627733020277, 42.908248189569535, 46.069679073215439, 49.228543693445843, 52.385312123112282], [7.8377378223268716, 11.811037107609447, 15.313615118517857, 18.670704965906724, 21.958290897126571, 25.206207715021249, 28.429037095235496, 31.634879502950644, 34.828638524084437, 38.013473399691765, 41.19151880917741, 44.364272633271975, 47.53281875312084, 50.697961822183806, 53.860312300118388], [8.919605734873789, 13.007711435388313, 16.573915129085334, 19.974342312352426, 23.293972585596648, 26.5667563757203, 29.809531451608321, 33.031769327150685, 36.239265816598239, 39.435790312675323, 42.623910919472727, 45.805442883111651, 48.981708325514764, 52.153694518185572, 55.322154420959698], [9.9946283820824834, 14.190361295800141, 17.817887841179873, 21.26093227125945, 24.612576377421522, 27.910524883974868, 31.173701563441602, 34.412862242025045, 37.634648706110989, 40.843415321050884, 44.04214994542435, 47.232978012841169, 50.417456447370186, 53.596753874948731, 56.771765754432457], [11.064090256031013, 15.361301343575925, 19.047949646361388, 22.532765416313869, 25.91620496332662, 29.2394205079349, 32.523270869465881, 35.779715464475261, 39.016196664616095, 42.237627509803703, 45.4474001519274, 48.647941127433196, 51.841036928216499, 55.028034667184916, 58.209970905250097], [12.128927704415439, 16.522284394784426, 20.265984501212254, 23.791669719454272, 27.206568881574774, 30.555020011020762, 33.859683872746356, 37.133649760307504, 40.385117593813002, 43.619533085646856, 46.840676630553575, 50.051265851897857, 53.253310556711732, 56.448332488918971, 59.637507005589829], [13.189846995683845, 17.674674253171487, 21.473493977824902, 25.03913093040942, 28.485081336558058, 31.858644293774859, 35.184165245422787, 38.475796636190897, 41.742455848758449, 44.990096293791186, 48.222870660068338, 51.443777308699826, 54.655042589416311, 57.858358441436511, 61.055036135780528], [14.247395665073945, 18.819555894710682, 22.671697117872794, 26.276375544903892, 29.752925495549038, 33.151412708998983, 36.497763772987645, 39.807134090704376, 43.089121522203808, 46.350163579538652, 49.594769786270069, 52.82620892320143, 56.046916910756961, 59.258751140598783, 62.463155567737854], [15.30200785858925, 19.957808654258601, 23.861599172945054, 27.504429642227545, 31.011103429019229, 34.434283425782942, 37.801385632318459, 41.128514139788358, 44.425913324440663, 47.700482714581842, 50.957073905278458, 54.199216028087261, 57.429547607017405, 60.65008661807661, 63.862406280068586], [16.354034360047551, 21.090156519983806, 25.044040298785627, 28.724161640881914, 32.260472459522644, 35.708083982611664, 39.095820003878235, 42.440684315990936, 45.75353669045622, 49.041718113283529, 52.310408280968073, 55.56338698149062, 58.803488508906895, 62.032886550960831, 65.253280088312461]] ynp_small_zeros = \ [[2.197141326031017, 5.4296810407941351, 8.5960058683311689, 11.749154830839881, 14.897442128336725, 18.043402276727856, 21.188068934142213, 24.331942571356912, 27.475294980449224, 30.618286491641115, 33.761017796109326, 36.90355531614295, 40.045944640266876, 43.188218097393211, 46.330399250701687], [3.6830228565851777, 6.9414999536541757, 10.123404655436613, 13.285758156782854, 16.440058007293282, 19.590241756629495, 22.738034717396327, 25.884314618788867, 29.029575819372535, 32.174118233366201, 35.318134458192094, 38.461753870997549, 41.605066618873108, 44.74813744908079, 47.891014070791065], [5.0025829314460639, 8.3507247014130795, 11.574195465217647, 14.760909306207676, 17.931285939466855, 21.092894504412739, 24.249231678519058, 27.402145837145258, 30.552708880564553, 33.70158627151572, 36.849213419846257, 39.995887376143356, 43.141817835750686, 46.287157097544201, 49.432018469138281], [6.2536332084598136, 9.6987879841487711, 12.972409052292216, 16.19044719506921, 19.38238844973613, 22.559791857764261, 25.728213194724094, 28.890678419054777, 32.048984005266337, 35.204266606440635, 38.357281675961019, 41.508551443818436, 44.658448731963676, 47.807246956681162, 50.95515126455207], [7.4649217367571329, 11.005169149809189, 14.3317235192331, 17.58443601710272, 20.801062338411128, 23.997004122902644, 27.179886689853435, 30.353960608554323, 33.521797098666792, 36.685048382072301, 39.844826969405863, 43.001910515625288, 46.15685955107263, 49.310088614282257, 52.461911043685864], [8.6495562436971983, 12.280868725807848, 15.660799304540377, 18.949739756016503, 22.192841809428241, 25.409072788867674, 28.608039283077593, 31.795195353138159, 34.973890634255288, 38.14630522169358, 41.313923188794905, 44.477791768537617, 47.638672065035628, 50.797131066967842, 53.953600129601663], [9.8147970120105779, 13.532811875789828, 16.965526446046053, 20.291285512443867, 23.56186260680065, 26.799499736027237, 30.015665481543419, 33.216968050039509, 36.407516858984748, 39.590015243560459, 42.766320595957378, 45.937754257017323, 49.105283450953203, 52.269633324547373, 55.431358715604255], [10.965152105242974, 14.765687379508912, 18.250123150217555, 21.612750053384621, 24.911310600813573, 28.171051927637585, 31.40518108895689, 34.621401012564177, 37.824552065973114, 41.017847386464902, 44.203512240871601, 47.3831408366063, 50.557907466622796, 53.728697478957026, 56.896191727313342], [12.103641941939539, 15.982840905145284, 19.517731005559611, 22.916962141504605, 26.243700855690533, 29.525960140695407, 32.778568197561124, 36.010261572392516, 39.226578757802172, 42.43122493258747, 45.626783824134354, 48.815117837929515, 51.997606404328863, 55.175294723956816, 58.348990221754937], [13.232403808592215, 17.186756572616758, 20.770762917490496, 24.206152448722253, 27.561059462697153, 30.866053571250639, 34.137476603379774, 37.385039772270268, 40.614946085165892, 43.831373184731238, 47.037251786726299, 50.234705848765229, 53.425316228549359, 56.610286079882087, 59.790548623216652], [14.35301374369987, 18.379337301642568, 22.011118775283494, 25.482116178696707, 28.865046588695164, 32.192853922166294, 35.483296655830277, 38.747005493021857, 41.990815194320955, 45.219355876831731, 48.435892856078888, 51.642803925173029, 54.84186659475857, 58.034439083840155, 61.221578745109862], [15.466672066554263, 19.562077985759503, 23.240325531101082, 26.746322986645901, 30.157042415639891, 33.507642948240263, 36.817212798512775, 40.097251300178642, 43.355193847719752, 46.596103410173672, 49.823567279972794, 53.040208868780832, 56.247996968470062, 59.448441365714251, 62.642721301357187], [16.574317035530872, 20.73617763753932, 24.459631728238804, 27.999993668839644, 31.438208790267783, 34.811512070805535, 38.140243708611251, 41.436725143893739, 44.708963264433333, 47.962435051891027, 51.201037321915983, 54.427630745992975, 57.644369734615238, 60.852911791989989, 64.054555435720397], [17.676697936439624, 21.9026148697762, 25.670073356263225, 29.244155124266438, 32.709534477396028, 36.105399554497548, 39.453272918267025, 42.766255701958017, 46.052899215578358, 49.319076602061401, 52.568982147952547, 55.805705507386287, 59.031580956740466, 62.248409689597653, 65.457606670836759], [18.774423978290318, 23.06220035979272, 26.872520985976736, 30.479680663499762, 33.971869047372436, 37.390118854896324, 40.757072537673599, 44.086572292170345, 47.387688809191869, 50.66667461073936, 53.928009929563275, 57.175005343085052, 60.410169281219877, 63.635442539153021, 66.85235358587768]] def test_bessel_zeros(): mp.dps = 15 for v in range(V): for m in range(1,M+1): print(v, m, "of", V, M) # Twice to test cache (if used) assert besseljzero(v,m).ae(jn_small_zeros[v][m-1]) assert besseljzero(v,m).ae(jn_small_zeros[v][m-1]) assert besseljzero(v,m,1).ae(jnp_small_zeros[v][m-1]) assert besseljzero(v,m,1).ae(jnp_small_zeros[v][m-1]) assert besselyzero(v,m).ae(yn_small_zeros[v][m-1]) assert besselyzero(v,m).ae(yn_small_zeros[v][m-1]) assert besselyzero(v,m,1).ae(ynp_small_zeros[v][m-1]) assert besselyzero(v,m,1).ae(ynp_small_zeros[v][m-1]) if __name__ == "__main__": test_bessel_zeros()
20,758
21.202139
65
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_matrices.py
from mpmath import * def test_matrix_basic(): A1 = matrix(3) for i in range(3): A1[i,i] = 1 assert A1 == eye(3) assert A1 == matrix(A1) A2 = matrix(3, 2) assert not A2._matrix__data A3 = matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert list(A3) == list(range(1, 10)) A3[1,1] = 0 assert not (1, 1) in A3._matrix__data A4 = matrix([[1, 2, 3], [4, 5, 6]]) A5 = matrix([[6, -1], [3, 2], [0, -3]]) assert A4 * A5 == matrix([[12, -6], [39, -12]]) assert A1 * A3 == A3 * A1 == A3 try: A2 * A2 assert False except ValueError: pass l = [[10, 20, 30], [40, 0, 60], [70, 80, 90]] A6 = matrix(l) assert A6.tolist() == l assert A6 == eval(repr(A6)) A6 = matrix(A6, force_type=float) assert A6 == eval(repr(A6)) assert A6*1j == eval(repr(A6*1j)) assert A3 * 10 == 10 * A3 == A6 assert A2.rows == 3 assert A2.cols == 2 A3.rows = 2 A3.cols = 2 assert len(A3._matrix__data) == 3 assert A4 + A4 == 2*A4 try: A4 + A2 except ValueError: pass assert sum(A1 - A1) == 0 A7 = matrix([[1, 2], [3, 4], [5, 6], [7, 8]]) x = matrix([10, -10]) assert A7*x == matrix([-10, -10, -10, -10]) A8 = ones(5) assert sum((A8 + 1) - (2 - zeros(5))) == 0 assert (1 + ones(4)) / 2 - 1 == zeros(4) assert eye(3)**10 == eye(3) try: A7**2 assert False except ValueError: pass A9 = randmatrix(3) A10 = matrix(A9) A9[0,0] = -100 assert A9 != A10 assert nstr(A9) def test_matrix_slices(): A = matrix([ [1, 2, 3], [4, 5 ,6], [7, 8 ,9]]) V = matrix([1,2,3,4,5]) # Get slice assert A[:,:] == A assert A[:,1] == matrix([[2],[5],[8]]) assert A[2,:] == matrix([[7, 8 ,9]]) assert A[1:3,1:3] == matrix([[5,6],[8,9]]) assert V[2:4] == matrix([3,4]) try: A6 = A[:,1:6] assert False except IndexError: pass # Assign slice with matrix A1 = matrix(3) A1[:,:] = A assert A1[:,:] == matrix([[1, 2, 3], [4, 5 ,6], [7, 8 ,9]]) A1[0,:] = matrix([[10, 11, 12]]) assert A1 == matrix([ [10, 11, 12], [4, 5 ,6], [7, 8 ,9]]) A1[:,2] = matrix([[13], [14], [15]]) assert A1 == matrix([ [10, 11, 13], [4, 5 ,14], [7, 8 ,15]]) A1[:2,:2] = matrix([[16, 17], [18 , 19]]) assert A1 == matrix([ [16, 17, 13], [18, 19 ,14], [7, 8 ,15]]) V[1:3] = 10 assert V == matrix([1,10,10,4,5]) try: A1[2,:] = A[:,1] assert False except ValueError: pass try: A1[2,1:20] = A[:,:] assert False except IndexError: pass # Assign slice with scalar A1[:,2] = 10 assert A1 == matrix([ [16, 17, 10], [18, 19 ,10], [7, 8 ,10]]) A1[:,:] = 40 for x in A1: assert x == 40 def test_matrix_power(): A = matrix([[1, 2], [3, 4]]) assert A**2 == A*A assert A**3 == A*A*A assert A**-1 == inverse(A) assert A**-2 == inverse(A*A) def test_matrix_transform(): A = matrix([[1, 2], [3, 4], [5, 6]]) assert A.T == A.transpose() == matrix([[1, 3, 5], [2, 4, 6]]) swap_row(A, 1, 2) assert A == matrix([[1, 2], [5, 6], [3, 4]]) l = [1, 2] swap_row(l, 0, 1) assert l == [2, 1] assert extend(eye(3), [1,2,3]) == matrix([[1,0,0,1],[0,1,0,2],[0,0,1,3]]) def test_matrix_conjugate(): A = matrix([[1 + j, 0], [2, j]]) assert A.conjugate() == matrix([[mpc(1, -1), 0], [2, mpc(0, -1)]]) assert A.transpose_conj() == A.H == matrix([[mpc(1, -1), 2], [0, mpc(0, -1)]]) def test_matrix_creation(): assert diag([1, 2, 3]) == matrix([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) A1 = ones(2, 3) assert A1.rows == 2 and A1.cols == 3 for a in A1: assert a == 1 A2 = zeros(3, 2) assert A2.rows == 3 and A2.cols == 2 for a in A2: assert a == 0 assert randmatrix(10) != randmatrix(10) one = mpf(1) assert hilbert(3) == matrix([[one, one/2, one/3], [one/2, one/3, one/4], [one/3, one/4, one/5]]) def test_norms(): # matrix norms A = matrix([[1, -2], [-3, -1], [2, 1]]) assert mnorm(A,1) == 6 assert mnorm(A,inf) == 4 assert mnorm(A,'F') == sqrt(20) # vector norms assert norm(-3) == 3 x = [1, -2, 7, -12] assert norm(x, 1) == 22 assert round(norm(x, 2), 10) == 14.0712472795 assert round(norm(x, 10), 10) == 12.0054633727 assert norm(x, inf) == 12 def test_vector(): x = matrix([0, 1, 2, 3, 4]) assert x == matrix([[0], [1], [2], [3], [4]]) assert x[3] == 3 assert len(x._matrix__data) == 4 assert list(x) == list(range(5)) x[0] = -10 x[4] = 0 assert x[0] == -10 assert len(x) == len(x.T) == 5 assert x.T*x == matrix([[114]]) def test_matrix_copy(): A = ones(6) B = A.copy() assert A == B B[0,0] = 0 assert A != B def test_matrix_numpy(): try: import numpy except ImportError: return l = [[1, 2], [3, 4], [5, 6]] a = numpy.matrix(l) assert matrix(l) == matrix(a)
5,591
26.820896
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_summation.py
from mpmath import * def test_sumem(): mp.dps = 15 assert sumem(lambda k: 1/k**2.5, [50, 100]).ae(0.0012524505324784962) assert sumem(lambda k: k**4 + 3*k + 1, [10, 100]).ae(2050333103) def test_nsum(): mp.dps = 15 assert nsum(lambda x: x**2, [1, 3]) == 14 assert nsum(lambda k: 1/factorial(k), [0, inf]).ae(e) assert nsum(lambda k: (-1)**(k+1) / k, [1, inf]).ae(log(2)) assert nsum(lambda k: (-1)**(k+1) / k**2, [1, inf]).ae(pi**2 / 12) assert nsum(lambda k: (-1)**k / log(k), [2, inf]).ae(0.9242998972229388) assert nsum(lambda k: 1/k**2, [1, inf]).ae(pi**2 / 6) assert nsum(lambda k: 2**k/fac(k), [0, inf]).ae(exp(2)) assert nsum(lambda k: 1/k**2, [4, inf], method='e').ae(0.2838229557371153) def test_nprod(): mp.dps = 15 assert nprod(lambda k: exp(1/k**2), [1,inf], method='r').ae(exp(pi**2/6)) assert nprod(lambda x: x**2, [1, 3]) == 36 def test_fsum(): mp.dps = 15 assert fsum([]) == 0 assert fsum([-4]) == -4 assert fsum([2,3]) == 5 assert fsum([1e-100,1]) == 1 assert fsum([1,1e-100]) == 1 assert fsum([1e100,1]) == 1e100 assert fsum([1,1e100]) == 1e100 assert fsum([1e-100,0]) == 1e-100 assert fsum([1e-100,1e100,1e-100]) == 1e100 assert fsum([2,1+1j,1]) == 4+1j assert fsum([2,inf,3]) == inf assert fsum([2,-1], absolute=1) == 3 assert fsum([2,-1], squared=1) == 5 assert fsum([1,1+j], squared=1) == 1+2j assert fsum([1,3+4j], absolute=1) == 6 assert fsum([1,2+3j], absolute=1, squared=1) == 14 assert isnan(fsum([inf,-inf])) assert fsum([inf,-inf], absolute=1) == inf assert fsum([inf,-inf], squared=1) == inf assert fsum([inf,-inf], absolute=1, squared=1) == inf assert iv.fsum([1,mpi(2,3)]) == mpi(3,4) def test_fprod(): mp.dps = 15 assert fprod([]) == 1 assert fprod([2,3]) == 6
1,859
34.769231
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_eigen.py
#!/usr/bin/python # -*- coding: utf-8 -*- from mpmath import mp from mpmath import libmp xrange = libmp.backend.xrange def run_hessenberg(A, verbose = 0): if verbose > 1: print("original matrix (hessenberg):\n", A) n = A.rows Q, H = mp.hessenberg(A) if verbose > 1: print("Q:\n",Q) print("H:\n",H) B = Q * H * Q.transpose_conj() eps = mp.exp(0.8 * mp.log(mp.eps)) err0 = 0 for x in xrange(n): for y in xrange(n): err0 += abs(A[y,x] - B[y,x]) err0 /= n * n err1 = 0 for x in xrange(n): for y in xrange(x + 2, n): err1 += abs(H[y,x]) if verbose > 0: print("difference (H):", err0, err1) if verbose > 1: print("B:\n", B) assert err0 < eps assert err1 == 0 def run_schur(A, verbose = 0): if verbose > 1: print("original matrix (schur):\n", A) n = A.rows Q, R = mp.schur(A) if verbose > 1: print("Q:\n", Q) print("R:\n", R) B = Q * R * Q.transpose_conj() C = Q * Q.transpose_conj() eps = mp.exp(0.8 * mp.log(mp.eps)) err0 = 0 for x in xrange(n): for y in xrange(n): err0 += abs(A[y,x] - B[y,x]) err0 /= n * n err1 = 0 for x in xrange(n): for y in xrange(n): if x == y: C[y,x] -= 1 err1 += abs(C[y,x]) err1 /= n * n err2 = 0 for x in xrange(n): for y in xrange(x + 1, n): err2 += abs(R[y,x]) if verbose > 0: print("difference (S):", err0, err1, err2) if verbose > 1: print("B:\n", B) assert err0 < eps assert err1 < eps assert err2 == 0 def run_eig(A, verbose = 0): if verbose > 1: print("original matrix (eig):\n", A) n = A.rows E, EL, ER = mp.eig(A, left = True, right = True) if verbose > 1: print("E:\n", E) print("EL:\n", EL) print("ER:\n", ER) eps = mp.exp(0.8 * mp.log(mp.eps)) err0 = 0 for i in xrange(n): B = A * ER[:,i] - E[i] * ER[:,i] err0 = max(err0, mp.mnorm(B)) B = EL[i,:] * A - EL[i,:] * E[i] err0 = max(err0, mp.mnorm(B)) err0 /= n * n if verbose > 0: print("difference (E):", err0) assert err0 < eps ##################### def test_eig_dyn(): v = 0 for i in xrange(5): n = 1 + int(mp.rand() * 5) if mp.rand() > 0.5: # real A = 2 * mp.randmatrix(n, n) - 1 if mp.rand() > 0.5: A *= 10 for x in xrange(n): for y in xrange(n): A[x,y] = int(A[x,y]) else: A = (2 * mp.randmatrix(n, n) - 1) + 1j * (2 * mp.randmatrix(n, n) - 1) if mp.rand() > 0.5: A *= 10 for x in xrange(n): for y in xrange(n): A[x,y] = int(mp.re(A[x,y])) + 1j * int(mp.im(A[x,y])) run_hessenberg(A, verbose = v) run_schur(A, verbose = v) run_eig(A, verbose = v) def test_eig(): v = 0 AS = [] A = mp.matrix([[2, 1, 0], # jordan block of size 3 [0, 2, 1], [0, 0, 2]]) AS.append(A) AS.append(A.transpose()) A = mp.matrix([[2, 0, 0], # jordan block of size 2 [0, 2, 1], [0, 0, 2]]) AS.append(A) AS.append(A.transpose()) A = mp.matrix([[2, 0, 1], # jordan block of size 2 [0, 2, 0], [0, 0, 2]]) AS.append(A) AS.append(A.transpose()) A= mp.matrix([[0, 0, 1], # cyclic [1, 0, 0], [0, 1, 0]]) AS.append(A) AS.append(A.transpose()) for A in AS: run_hessenberg(A, verbose = v) run_schur(A, verbose = v) run_eig(A, verbose = v)
3,905
20.7
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_linalg.py
# TODO: don't use round from __future__ import division from mpmath import * xrange = libmp.backend.xrange # XXX: these shouldn't be visible(?) LU_decomp = mp.LU_decomp L_solve = mp.L_solve U_solve = mp.U_solve householder = mp.householder improve_solution = mp.improve_solution A1 = matrix([[3, 1, 6], [2, 1, 3], [1, 1, 1]]) b1 = [2, 7, 4] A2 = matrix([[ 2, -1, -1, 2], [ 6, -2, 3, -1], [-4, 2, 3, -2], [ 2, 0, 4, -3]]) b2 = [3, -3, -2, -1] A3 = matrix([[ 1, 0, -1, -1, 0], [ 0, 1, 1, 0, -1], [ 4, -5, 2, 0, 0], [ 0, 0, -2, 9,-12], [ 0, 5, 0, 0, 12]]) b3 = [0, 0, 0, 0, 50] A4 = matrix([[10.235, -4.56, 0., -0.035, 5.67], [-2.463, 1.27, 3.97, -8.63, 1.08], [-6.58, 0.86, -0.257, 9.32, -43.6 ], [ 9.83, 7.39, -17.25, 0.036, 24.86], [-9.31, 34.9, 78.56, 1.07, 65.8 ]]) b4 = [8.95, 20.54, 7.42, 5.60, 58.43] A5 = matrix([[ 1, 2, -4], [-2, -3, 5], [ 3, 5, -8]]) A6 = matrix([[ 1.377360, 2.481400, 5.359190], [ 2.679280, -1.229560, 25.560210], [-1.225280+1.e6, 9.910180, -35.049900-1.e6]]) b6 = [23.500000, -15.760000, 2.340000] A7 = matrix([[1, -0.5], [2, 1], [-2, 6]]) b7 = [3, 2, -4] A8 = matrix([[1, 2, 3], [-1, 0, 1], [-1, -2, -1], [1, 0, -1]]) b8 = [1, 2, 3, 4] A9 = matrix([[ 4, 2, -2], [ 2, 5, -4], [-2, -4, 5.5]]) b9 = [10, 16, -15.5] A10 = matrix([[1.0 + 1.0j, 2.0, 2.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) b10 = [1.0, 1.0 + 1.0j, 1.0] def test_LU_decomp(): A = A3.copy() b = b3 A, p = LU_decomp(A) y = L_solve(A, b, p) x = U_solve(A, y) assert p == [2, 1, 2, 3] assert [round(i, 14) for i in x] == [3.78953107960742, 2.9989094874591098, -0.081788440567070006, 3.8713195201744801, 2.9171210468920399] A = A4.copy() b = b4 A, p = LU_decomp(A) y = L_solve(A, b, p) x = U_solve(A, y) assert p == [0, 3, 4, 3] assert [round(i, 14) for i in x] == [2.6383625899619201, 2.6643834462368399, 0.79208015947958998, -2.5088376454101899, -1.0567657691375001] A = randmatrix(3) bak = A.copy() LU_decomp(A, overwrite=1) assert A != bak def test_inverse(): for A in [A1, A2, A5]: inv = inverse(A) assert mnorm(A*inv - eye(A.rows), 1) < 1.e-14 def test_householder(): mp.dps = 15 A, b = A8, b8 H, p, x, r = householder(extend(A, b)) assert H == matrix( [[mpf('3.0'), mpf('-2.0'), mpf('-1.0'), 0], [-1.0,mpf('3.333333333333333'),mpf('-2.9999999999999991'),mpf('2.0')], [-1.0, mpf('-0.66666666666666674'),mpf('2.8142135623730948'), mpf('-2.8284271247461898')], [1.0, mpf('-1.3333333333333333'),mpf('-0.20000000000000018'), mpf('4.2426406871192857')]]) assert p == [-2, -2, mpf('-1.4142135623730949')] assert round(norm(r, 2), 10) == 4.2426406870999998 y = [102.102, 58.344, 36.463, 24.310, 17.017, 12.376, 9.282, 7.140, 5.610, 4.488, 3.6465, 3.003] def coeff(n): # similiar to Hilbert matrix A = [] for i in range(1, 13): A.append([1. / (i + j - 1) for j in range(1, n + 1)]) return matrix(A) residuals = [] refres = [] for n in range(2, 7): A = coeff(n) H, p, x, r = householder(extend(A, y)) x = matrix(x) y = matrix(y) residuals.append(norm(r, 2)) refres.append(norm(residual(A, x, y), 2)) assert [round(res, 10) for res in residuals] == [15.1733888877, 0.82378073210000002, 0.302645887, 0.0260109244, 0.00058653999999999998] assert norm(matrix(residuals) - matrix(refres), inf) < 1.e-13 def test_factorization(): A = randmatrix(5) P, L, U = lu(A) assert mnorm(P*A - L*U, 1) < 1.e-15 def test_solve(): assert norm(residual(A6, lu_solve(A6, b6), b6), inf) < 1.e-10 assert norm(residual(A7, lu_solve(A7, b7), b7), inf) < 1.5 assert norm(residual(A8, lu_solve(A8, b8), b8), inf) <= 3 + 1.e-10 assert norm(residual(A6, qr_solve(A6, b6)[0], b6), inf) < 1.e-10 assert norm(residual(A7, qr_solve(A7, b7)[0], b7), inf) < 1.5 assert norm(residual(A8, qr_solve(A8, b8)[0], b8), 2) <= 4.3 assert norm(residual(A10, lu_solve(A10, b10), b10), 2) < 1.e-10 assert norm(residual(A10, qr_solve(A10, b10)[0], b10), 2) < 1.e-10 def test_solve_overdet_complex(): A = matrix([[1, 2j], [3, 4j], [5, 6]]) b = matrix([1 + j, 2, -j]) assert norm(residual(A, lu_solve(A, b), b)) < 1.0208 def test_singular(): mp.dps = 15 A = [[5.6, 1.2], [7./15, .1]] B = repr(zeros(2)) b = [1, 2] def _assert_ZeroDivisionError(statement): try: eval(statement) assert False except (ZeroDivisionError, ValueError): pass for i in ['lu_solve(%s, %s)' % (A, b), 'lu_solve(%s, %s)' % (B, b), 'qr_solve(%s, %s)' % (A, b), 'qr_solve(%s, %s)' % (B, b)]: _assert_ZeroDivisionError(i) def test_cholesky(): assert fp.cholesky(fp.matrix(A9)) == fp.matrix([[2, 0, 0], [1, 2, 0], [-1, -3/2, 3/2]]) x = fp.cholesky_solve(A9, b9) assert fp.norm(fp.residual(A9, x, b9), fp.inf) == 0 def test_det(): assert det(A1) == 1 assert round(det(A2), 14) == 8 assert round(det(A3)) == 1834 assert round(det(A4)) == 4443376 assert det(A5) == 1 assert round(det(A6)) == 78356463 assert det(zeros(3)) == 0 def test_cond(): mp.dps = 15 A = matrix([[1.2969, 0.8648], [0.2161, 0.1441]]) assert cond(A, lambda x: mnorm(x,1)) == mpf('327065209.73817754') assert cond(A, lambda x: mnorm(x,inf)) == mpf('327065209.73817754') assert cond(A, lambda x: mnorm(x,'F')) == mpf('249729266.80008656') @extradps(50) def test_precision(): A = randmatrix(10, 10) assert mnorm(inverse(inverse(A)) - A, 1) < 1.e-45 def test_interval_matrix(): mp.dps = 15 iv.dps = 15 a = iv.matrix([['0.1','0.3','1.0'],['7.1','5.5','4.8'],['3.2','4.4','5.6']]) b = iv.matrix(['4','0.6','0.5']) c = iv.lu_solve(a, b) assert c[0].delta < 1e-13 assert c[1].delta < 1e-13 assert c[2].delta < 1e-13 assert 5.25823271130625686059275 in c[0] assert -13.155049396267837541163 in c[1] assert 7.42069154774972557628979 in c[2] def test_LU_cache(): A = randmatrix(3) LU = LU_decomp(A) assert A._LU == LU_decomp(A) A[0,0] = -1000 assert A._LU is None def test_improve_solution(): A = randmatrix(5, min=1e-20, max=1e20) b = randmatrix(5, 1, min=-1000, max=1000) x1 = lu_solve(A, b) + randmatrix(5, 1, min=-1e-5, max=1.e-5) x2 = improve_solution(A, x1, b) assert norm(residual(A, x2, b), 2) < norm(residual(A, x1, b), 2) def test_exp_pade(): for i in range(3): dps = 15 extra = 15 mp.dps = dps + extra dm = 0 N = 3 dg = range(1,N+1) a = diag(dg) expa = diag([exp(x) for x in dg]) # choose a random matrix not close to be singular # to avoid adding too much extra precision in computing # m**-1 * M * m while abs(dm) < 0.01: m = randmatrix(N) dm = det(m) m = m/dm a1 = m**-1 * a * m e2 = m**-1 * expa * m mp.dps = dps e1 = expm(a1, method='pade') mp.dps = dps + extra d = e2 - e1 #print d mp.dps = dps assert norm(d, inf).ae(0) mp.dps = 15 def test_qr(): mp.dps = 15 # used default value for dps lowlimit = -9 # lower limit of matrix element value uplimit = 9 # uppter limit of matrix element value maxm = 4 # max matrix size flg = False # toggle to create real vs complex matrix zero = mpf('0.0') for k in xrange(0,10): exdps = 0 mode = 'full' flg = bool(k % 2) # generate arbitrary matrix size (2 to maxm) num1 = nint(2 + (maxm-2)*rand()) num2 = nint(2 + (maxm-2)*rand()) m = int(max(num1, num2)) n = int(min(num1, num2)) # create matrix A = mp.matrix(m,n) # populate matrix values with arbitrary integers if flg: flg = False dtype = 'complex' for j in xrange(0,n): for i in xrange(0,m): val = nint(lowlimit + (uplimit-lowlimit)*rand()) val2 = nint(lowlimit + (uplimit-lowlimit)*rand()) A[i,j] = mpc(val, val2) else: flg = True dtype = 'real' for j in xrange(0,n): for i in xrange(0,m): val = nint(lowlimit + (uplimit-lowlimit)*rand()) A[i,j] = mpf(val) # perform A -> QR decomposition Q, R = qr(A, mode, edps = exdps) #print('\n\n A = \n', nstr(A, 4)) #print('\n Q = \n', nstr(Q, 4)) #print('\n R = \n', nstr(R, 4)) #print('\n Q*R = \n', nstr(Q*R, 4)) maxnorm = mpf('1.0E-11') n1 = norm(A - Q * R) #print '\n Norm of A - Q * R = ', n1 if n1 > maxnorm: raise ValueError('Excessive norm value') if dtype == 'real': n1 = norm(eye(m) - Q.T * Q) #print ' Norm of I - Q.T * Q = ', n1 if n1 > maxnorm: raise ValueError('Excessive norm value') n1 = norm(eye(m) - Q * Q.T) #print ' Norm of I - Q * Q.T = ', n1 if n1 > maxnorm: raise ValueError('Excessive norm value') if dtype == 'complex': n1 = norm(eye(m) - Q.T * Q.conjugate()) #print ' Norm of I - Q.T * Q.conjugate() = ', n1 if n1 > maxnorm: raise ValueError('Excessive norm value') n1 = norm(eye(m) - Q.conjugate() * Q.T) #print ' Norm of I - Q.conjugate() * Q.T = ', n1 if n1 > maxnorm: raise ValueError('Excessive norm value')
10,263
30.484663
91
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/__init__.py
0
0
0
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_trig.py
from mpmath import * from mpmath.libmp import * def test_trig_misc_hard(): mp.prec = 53 # Worst-case input for an IEEE double, from a paper by Kahan x = ldexp(6381956970095103,797) assert cos(x) == mpf('-4.6871659242546277e-19') assert sin(x) == 1 mp.prec = 150 a = mpf(10**50) mp.prec = 53 assert sin(a).ae(-0.7896724934293100827) assert cos(a).ae(-0.6135286082336635622) # Check relative accuracy close to x = zero assert sin(1e-100) == 1e-100 # when rounding to nearest assert sin(1e-6).ae(9.999999999998333e-007, rel_eps=2e-15, abs_eps=0) assert sin(1e-6j).ae(1.0000000000001666e-006j, rel_eps=2e-15, abs_eps=0) assert sin(-1e-6j).ae(-1.0000000000001666e-006j, rel_eps=2e-15, abs_eps=0) assert cos(1e-100) == 1 assert cos(1e-6).ae(0.9999999999995) assert cos(-1e-6j).ae(1.0000000000005) assert tan(1e-100) == 1e-100 assert tan(1e-6).ae(1.0000000000003335e-006, rel_eps=2e-15, abs_eps=0) assert tan(1e-6j).ae(9.9999999999966644e-007j, rel_eps=2e-15, abs_eps=0) assert tan(-1e-6j).ae(-9.9999999999966644e-007j, rel_eps=2e-15, abs_eps=0) def test_trig_near_zero(): mp.dps = 15 for r in [round_nearest, round_down, round_up, round_floor, round_ceiling]: assert sin(0, rounding=r) == 0 assert cos(0, rounding=r) == 1 a = mpf('1e-100') b = mpf('-1e-100') assert sin(a, rounding=round_nearest) == a assert sin(a, rounding=round_down) < a assert sin(a, rounding=round_floor) < a assert sin(a, rounding=round_up) >= a assert sin(a, rounding=round_ceiling) >= a assert sin(b, rounding=round_nearest) == b assert sin(b, rounding=round_down) > b assert sin(b, rounding=round_floor) <= b assert sin(b, rounding=round_up) <= b assert sin(b, rounding=round_ceiling) > b assert cos(a, rounding=round_nearest) == 1 assert cos(a, rounding=round_down) < 1 assert cos(a, rounding=round_floor) < 1 assert cos(a, rounding=round_up) == 1 assert cos(a, rounding=round_ceiling) == 1 assert cos(b, rounding=round_nearest) == 1 assert cos(b, rounding=round_down) < 1 assert cos(b, rounding=round_floor) < 1 assert cos(b, rounding=round_up) == 1 assert cos(b, rounding=round_ceiling) == 1 def test_trig_near_n_pi(): mp.dps = 15 a = [n*pi for n in [1, 2, 6, 11, 100, 1001, 10000, 100001]] mp.dps = 135 a.append(10**100 * pi) mp.dps = 15 assert sin(a[0]) == mpf('1.2246467991473531772e-16') assert sin(a[1]) == mpf('-2.4492935982947063545e-16') assert sin(a[2]) == mpf('-7.3478807948841190634e-16') assert sin(a[3]) == mpf('4.8998251578625894243e-15') assert sin(a[4]) == mpf('1.9643867237284719452e-15') assert sin(a[5]) == mpf('-8.8632615209684813458e-15') assert sin(a[6]) == mpf('-4.8568235395684898392e-13') assert sin(a[7]) == mpf('3.9087342299491231029e-11') assert sin(a[8]) == mpf('-1.369235466754566993528e-36') r = round_nearest assert cos(a[0], rounding=r) == -1 assert cos(a[1], rounding=r) == 1 assert cos(a[2], rounding=r) == 1 assert cos(a[3], rounding=r) == -1 assert cos(a[4], rounding=r) == 1 assert cos(a[5], rounding=r) == -1 assert cos(a[6], rounding=r) == 1 assert cos(a[7], rounding=r) == -1 assert cos(a[8], rounding=r) == 1 r = round_up assert cos(a[0], rounding=r) == -1 assert cos(a[1], rounding=r) == 1 assert cos(a[2], rounding=r) == 1 assert cos(a[3], rounding=r) == -1 assert cos(a[4], rounding=r) == 1 assert cos(a[5], rounding=r) == -1 assert cos(a[6], rounding=r) == 1 assert cos(a[7], rounding=r) == -1 assert cos(a[8], rounding=r) == 1 r = round_down assert cos(a[0], rounding=r) > -1 assert cos(a[1], rounding=r) < 1 assert cos(a[2], rounding=r) < 1 assert cos(a[3], rounding=r) > -1 assert cos(a[4], rounding=r) < 1 assert cos(a[5], rounding=r) > -1 assert cos(a[6], rounding=r) < 1 assert cos(a[7], rounding=r) > -1 assert cos(a[8], rounding=r) < 1 r = round_floor assert cos(a[0], rounding=r) == -1 assert cos(a[1], rounding=r) < 1 assert cos(a[2], rounding=r) < 1 assert cos(a[3], rounding=r) == -1 assert cos(a[4], rounding=r) < 1 assert cos(a[5], rounding=r) == -1 assert cos(a[6], rounding=r) < 1 assert cos(a[7], rounding=r) == -1 assert cos(a[8], rounding=r) < 1 r = round_ceiling assert cos(a[0], rounding=r) > -1 assert cos(a[1], rounding=r) == 1 assert cos(a[2], rounding=r) == 1 assert cos(a[3], rounding=r) > -1 assert cos(a[4], rounding=r) == 1 assert cos(a[5], rounding=r) > -1 assert cos(a[6], rounding=r) == 1 assert cos(a[7], rounding=r) > -1 assert cos(a[8], rounding=r) == 1 mp.dps = 15 if __name__ == '__main__': for f in globals().keys(): if f.startswith("test_"): print(f) globals()[f]()
4,940
33.552448
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_mpmath.py
from mpmath.libmp import * from mpmath import * def test_newstyle_classes(): for cls in [mp, fp, iv, mpf, mpc]: for s in cls.__class__.__mro__: assert isinstance(s, type)
196
23.625
39
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_fp.py
""" Easy-to-use test-generating code: cases = ''' exp 2.25 log 2.25 ''' from mpmath import * mp.dps = 20 for test in cases.splitlines(): if not test: continue words = test.split() fname = words[0] args = words[1:] argstr = ", ".join(args) testline = "%s(%s)" % (fname, argstr) ans = str(eval(testline)) print " assert ae(fp.%s, %s)" % (testline, ans) """ from mpmath import fp def ae(x, y, tol=1e-12): if x == y: return True return abs(x-y) <= tol*abs(y) def test_conj(): assert fp.conj(4) == 4 assert fp.conj(3+4j) == 3-4j assert fp.fdot([1,2],[3,2+1j], conjugate=True) == 7-2j def test_fp_number_parts(): assert ae(fp.arg(3), 0.0) assert ae(fp.arg(-3), 3.1415926535897932385) assert ae(fp.arg(3j), 1.5707963267948966192) assert ae(fp.arg(-3j), -1.5707963267948966192) assert ae(fp.arg(2+3j), 0.98279372324732906799) assert ae(fp.arg(-1-1j), -2.3561944901923449288) assert ae(fp.re(2.5), 2.5) assert ae(fp.re(2.5+3j), 2.5) assert ae(fp.im(2.5), 0.0) assert ae(fp.im(2.5+3j), 3.0) assert ae(fp.floor(2.5), 2.0) assert ae(fp.floor(2), 2.0) assert ae(fp.floor(2.0+0j), (2.0 + 0.0j)) assert ae(fp.floor(-1.5-0.5j), (-2.0 - 1.0j)) assert ae(fp.ceil(2.5), 3.0) assert ae(fp.ceil(2), 2.0) assert ae(fp.ceil(2.0+0j), (2.0 + 0.0j)) assert ae(fp.ceil(-1.5-0.5j), (-1.0 + 0.0j)) def test_fp_cospi_sinpi(): assert ae(fp.sinpi(0), 0.0) assert ae(fp.sinpi(0.25), 0.7071067811865475244) assert ae(fp.sinpi(0.5), 1.0) assert ae(fp.sinpi(0.75), 0.7071067811865475244) assert ae(fp.sinpi(1), 0.0) assert ae(fp.sinpi(1.25), -0.7071067811865475244) assert ae(fp.sinpi(1.5), -1.0) assert ae(fp.sinpi(1.75), -0.7071067811865475244) assert ae(fp.sinpi(2), 0.0) assert ae(fp.sinpi(2.25), 0.7071067811865475244) assert ae(fp.sinpi(0+3j), (0.0 + 6195.8238636085899556j)) assert ae(fp.sinpi(0.25+3j), (4381.1091260582448033 + 4381.1090689950686908j)) assert ae(fp.sinpi(0.5+3j), (6195.8239443081075259 + 0.0j)) assert ae(fp.sinpi(0.75+3j), (4381.1091260582448033 - 4381.1090689950686908j)) assert ae(fp.sinpi(1+3j), (0.0 - 6195.8238636085899556j)) assert ae(fp.sinpi(1.25+3j), (-4381.1091260582448033 - 4381.1090689950686908j)) assert ae(fp.sinpi(1.5+3j), (-6195.8239443081075259 + 0.0j)) assert ae(fp.sinpi(1.75+3j), (-4381.1091260582448033 + 4381.1090689950686908j)) assert ae(fp.sinpi(2+3j), (0.0 + 6195.8238636085899556j)) assert ae(fp.sinpi(2.25+3j), (4381.1091260582448033 + 4381.1090689950686908j)) assert ae(fp.sinpi(-0.75), -0.7071067811865475244) assert ae(fp.sinpi(-1e-10), -3.1415926535897933529e-10) assert ae(fp.sinpi(1e-10), 3.1415926535897933529e-10) assert ae(fp.sinpi(1e-10+1e-10j), (3.141592653589793353e-10 + 3.1415926535897933528e-10j)) assert ae(fp.sinpi(1e-10-1e-10j), (3.141592653589793353e-10 - 3.1415926535897933528e-10j)) assert ae(fp.sinpi(-1e-10+1e-10j), (-3.141592653589793353e-10 + 3.1415926535897933528e-10j)) assert ae(fp.sinpi(-1e-10-1e-10j), (-3.141592653589793353e-10 - 3.1415926535897933528e-10j)) assert ae(fp.cospi(0), 1.0) assert ae(fp.cospi(0.25), 0.7071067811865475244) assert ae(fp.cospi(0.5), 0.0) assert ae(fp.cospi(0.75), -0.7071067811865475244) assert ae(fp.cospi(1), -1.0) assert ae(fp.cospi(1.25), -0.7071067811865475244) assert ae(fp.cospi(1.5), 0.0) assert ae(fp.cospi(1.75), 0.7071067811865475244) assert ae(fp.cospi(2), 1.0) assert ae(fp.cospi(2.25), 0.7071067811865475244) assert ae(fp.cospi(0+3j), (6195.8239443081075259 + 0.0j)) assert ae(fp.cospi(0.25+3j), (4381.1091260582448033 - 4381.1090689950686908j)) assert ae(fp.cospi(0.5+3j), (0.0 - 6195.8238636085899556j)) assert ae(fp.cospi(0.75+3j), (-4381.1091260582448033 - 4381.1090689950686908j)) assert ae(fp.cospi(1+3j), (-6195.8239443081075259 + 0.0j)) assert ae(fp.cospi(1.25+3j), (-4381.1091260582448033 + 4381.1090689950686908j)) assert ae(fp.cospi(1.5+3j), (0.0 + 6195.8238636085899556j)) assert ae(fp.cospi(1.75+3j), (4381.1091260582448033 + 4381.1090689950686908j)) assert ae(fp.cospi(2+3j), (6195.8239443081075259 + 0.0j)) assert ae(fp.cospi(2.25+3j), (4381.1091260582448033 - 4381.1090689950686908j)) assert ae(fp.cospi(-0.75), -0.7071067811865475244) assert ae(fp.sinpi(-0.7), -0.80901699437494750611) assert ae(fp.cospi(-0.7), -0.5877852522924730163) assert ae(fp.cospi(-3+2j), (-267.74676148374822225 + 0.0j)) assert ae(fp.sinpi(-3+2j), (0.0 - 267.74489404101651426j)) assert ae(fp.sinpi(-0.7+2j), (-216.6116802292079471 - 157.37650009392034693j)) assert ae(fp.cospi(-0.7+2j), (-157.37759774921754565 + 216.61016943630197336j)) def test_fp_expj(): assert ae(fp.expj(0), (1.0 + 0.0j)) assert ae(fp.expj(1), (0.5403023058681397174 + 0.84147098480789650665j)) assert ae(fp.expj(2), (-0.416146836547142387 + 0.9092974268256816954j)) assert ae(fp.expj(0.75), (0.73168886887382088631 + 0.68163876002333416673j)) assert ae(fp.expj(2+3j), (-0.020718731002242879378 + 0.045271253156092975488j)) assert ae(fp.expjpi(0), (1.0 + 0.0j)) assert ae(fp.expjpi(1), (-1.0 + 0.0j)) assert ae(fp.expjpi(2), (1.0 + 0.0j)) assert ae(fp.expjpi(0.75), (-0.7071067811865475244 + 0.7071067811865475244j)) assert ae(fp.expjpi(2+3j), (0.000080699517570304599239 + 0.0j)) def test_fp_bernoulli(): assert ae(fp.bernoulli(0), 1.0) assert ae(fp.bernoulli(1), -0.5) assert ae(fp.bernoulli(2), 0.16666666666666666667) assert ae(fp.bernoulli(10), 0.075757575757575757576) assert ae(fp.bernoulli(11), 0.0) def test_fp_gamma(): assert ae(fp.gamma(1), 1.0) assert ae(fp.gamma(1.5), 0.88622692545275801365) assert ae(fp.gamma(10), 362880.0) assert ae(fp.gamma(-0.5), -3.5449077018110320546) assert ae(fp.gamma(-7.1), 0.0016478244570263333622) assert ae(fp.gamma(12.3), 83385367.899970000963) assert ae(fp.gamma(2+0j), (1.0 + 0.0j)) assert ae(fp.gamma(-2.5+0j), (-0.94530872048294188123 + 0.0j)) assert ae(fp.gamma(3+4j), (0.0052255384713692141947 - 0.17254707929430018772j)) assert ae(fp.gamma(-3-4j), (0.00001460997305874775607 - 0.000020760733311509070396j)) assert ae(fp.fac(0), 1.0) assert ae(fp.fac(1), 1.0) assert ae(fp.fac(20), 2432902008176640000.0) assert ae(fp.fac(-3.5), -0.94530872048294188123) assert ae(fp.fac(2+3j), (-0.44011340763700171113 - 0.06363724312631702183j)) assert ae(fp.loggamma(1.0), 0.0) assert ae(fp.loggamma(2.0), 0.0) assert ae(fp.loggamma(3.0), 0.69314718055994530942) assert ae(fp.loggamma(7.25), 7.0521854507385394449) assert ae(fp.loggamma(1000.0), 5905.2204232091812118) assert ae(fp.loggamma(1e50), 1.1412925464970229298e+52) assert ae(fp.loggamma(1e25+1e25j), (5.6125802751733671621e+26 + 5.7696599078528568383e+26j)) assert ae(fp.loggamma(3+4j), (-1.7566267846037841105 + 4.7426644380346579282j)) assert ae(fp.loggamma(-0.5), (1.2655121234846453965 - 3.1415926535897932385j)) assert ae(fp.loggamma(-1.25), (1.3664317612369762346 - 6.2831853071795864769j)) assert ae(fp.loggamma(-2.75), (0.0044878975359557733115 - 9.4247779607693797154j)) assert ae(fp.loggamma(-3.5), (-1.3090066849930420464 - 12.566370614359172954j)) assert ae(fp.loggamma(-4.5), (-2.8130840817693161197 - 15.707963267948966192j)) assert ae(fp.loggamma(-2+3j), (-6.776523813485657093 - 4.568791367260286402j)) assert ae(fp.loggamma(-1000.3), (-5912.8440347785205041 - 3144.7342462433830317j)) assert ae(fp.loggamma(-100-100j), (-632.35117666833135562 - 158.37641469650352462j)) assert ae(fp.loggamma(1e-10), 23.025850929882735237) assert ae(fp.loggamma(-1e-10), (23.02585092999817837 - 3.1415926535897932385j)) assert ae(fp.loggamma(1e-10j), (23.025850929940456804 - 1.5707963268526181857j)) assert ae(fp.loggamma(1e-10j-1e-10), (22.679277339718205716 - 2.3561944902500664954j)) def test_fp_psi(): assert ae(fp.psi(0, 3.7), 1.1671535393615114409) assert ae(fp.psi(0, 0.5), -1.9635100260214234794) assert ae(fp.psi(0, 1), -0.57721566490153286061) assert ae(fp.psi(0, -2.5), 1.1031566406452431872) assert ae(fp.psi(0, 12.9), 2.5179671503279156347) assert ae(fp.psi(0, 100), 4.6001618527380874002) assert ae(fp.psi(0, 2500.3), 7.8239660143238547877) assert ae(fp.psi(0, 1e40), 92.103403719761827391) assert ae(fp.psi(0, 1e200), 460.51701859880913677) assert ae(fp.psi(0, 3.7+0j), (1.1671535393615114409 + 0.0j)) assert ae(fp.psi(1, 3), 0.39493406684822643647) assert ae(fp.psi(3, 2+3j), (-0.05383196209159972116 + 0.0076890935247364805218j)) assert ae(fp.psi(4, -0.5+1j), (1.2719531355492328195 - 18.211833410936276774j)) assert ae(fp.harmonic(0), 0.0) assert ae(fp.harmonic(1), 1.0) assert ae(fp.harmonic(2), 1.5) assert ae(fp.harmonic(100), 5.1873775176396202608) assert ae(fp.harmonic(-2.5), 1.2803723055467760478) assert ae(fp.harmonic(2+3j), (1.9390425294578375875 + 0.87336044981834544043j)) assert ae(fp.harmonic(-5-4j), (2.3725754822349437733 - 2.4160904444801621j)) def test_fp_zeta(): assert ae(fp.zeta(1e100), 1.0) assert ae(fp.zeta(3), 1.2020569031595942854) assert ae(fp.zeta(2+0j), (1.6449340668482264365 + 0.0j)) assert ae(fp.zeta(0.93), -13.713619351638164784) assert ae(fp.zeta(1.74), 1.9796863545771774095) assert ae(fp.zeta(0.0), -0.5) assert ae(fp.zeta(-1.0), -0.083333333333333333333) assert ae(fp.zeta(-2.0), 0.0) assert ae(fp.zeta(-3.0), 0.0083333333333333333333) assert ae(fp.zeta(-500.0), 0.0) assert ae(fp.zeta(-7.4), 0.0036537321227995882447) assert ae(fp.zeta(2.1), 1.5602165335033620158) assert ae(fp.zeta(26.9), 1.0000000079854809935) assert ae(fp.zeta(26), 1.0000000149015548284) assert ae(fp.zeta(27), 1.0000000074507117898) assert ae(fp.zeta(28), 1.0000000037253340248) assert ae(fp.zeta(27.1), 1.000000006951755045) assert ae(fp.zeta(32.7), 1.0000000001433243232) assert ae(fp.zeta(100), 1.0) assert ae(fp.altzeta(3.5), 0.92755357777394803511) assert ae(fp.altzeta(1), 0.69314718055994530942) assert ae(fp.altzeta(2), 0.82246703342411321824) assert ae(fp.altzeta(0), 0.5) assert ae(fp.zeta(-2+3j, 1), (0.13297115587929864827 + 0.12305330040458776494j)) assert ae(fp.zeta(-2+3j, 5), (18.384866151867576927 - 11.377015110597711009j)) assert ae(fp.zeta(1.0000000001), 9999999173.1735741337) assert ae(fp.zeta(0.9999999999), -9999999172.0191428039) assert ae(fp.zeta(1+0.000000001j), (0.57721566490153286061 - 999999999.99999993765j)) assert ae(fp.primezeta(2.5+4j), (-0.16922458243438033385 - 0.010847965298387727811j)) assert ae(fp.primezeta(4), 0.076993139764246844943) assert ae(fp.riemannr(3.7), 2.3034079839110855717) assert ae(fp.riemannr(8), 3.9011860449341499474) assert ae(fp.riemannr(3+4j), (2.2369653314259991796 + 1.6339943856990281694j)) def test_fp_hyp2f1(): assert ae(fp.hyp2f1(1, (3,2), 3.25, 5.0), (-0.46600275923108143059 - 0.74393667908854842325j)) assert ae(fp.hyp2f1(1+1j, (3,2), 3.25, 5.0), (-5.9208875603806515987 - 2.3813557707889590686j)) assert ae(fp.hyp2f1(1+1j, (3,2), 3.25, 2+3j), (0.17174552030925080445 + 0.19589781970539389999j)) def test_fp_erf(): assert fp.erf(2) == fp.erf(2.0) == fp.erf(2.0+0.0j) assert fp.erf(fp.inf) == 1.0 assert fp.erf(fp.ninf) == -1.0 assert ae(fp.erf(0), 0.0) assert ae(fp.erf(-0), -0.0) assert ae(fp.erf(0.3), 0.32862675945912741619) assert ae(fp.erf(-0.3), -0.32862675945912741619) assert ae(fp.erf(0.9), 0.79690821242283213966) assert ae(fp.erf(-0.9), -0.79690821242283213966) assert ae(fp.erf(1.0), 0.84270079294971486934) assert ae(fp.erf(-1.0), -0.84270079294971486934) assert ae(fp.erf(1.1), 0.88020506957408172966) assert ae(fp.erf(-1.1), -0.88020506957408172966) assert ae(fp.erf(8.5), 1.0) assert ae(fp.erf(-8.5), -1.0) assert ae(fp.erf(9.1), 1.0) assert ae(fp.erf(-9.1), -1.0) assert ae(fp.erf(20.0), 1.0) assert ae(fp.erf(-20.0), -1.0) assert ae(fp.erf(10000.0), 1.0) assert ae(fp.erf(-10000.0), -1.0) assert ae(fp.erf(1e+50), 1.0) assert ae(fp.erf(-1e+50), -1.0) assert ae(fp.erf(1j), 1.650425758797542876j) assert ae(fp.erf(-1j), -1.650425758797542876j) assert ae(fp.erf((2+3j)), (-20.829461427614568389 + 8.6873182714701631444j)) assert ae(fp.erf(-(2+3j)), -(-20.829461427614568389 + 8.6873182714701631444j)) assert ae(fp.erf((8+9j)), (-1072004.2525062051158 + 364149.91954310255423j)) assert ae(fp.erf(-(8+9j)), -(-1072004.2525062051158 + 364149.91954310255423j)) assert fp.erfc(fp.inf) == 0.0 assert fp.erfc(fp.ninf) == 2.0 assert fp.erfc(0) == 1 assert fp.erfc(-0.0) == 1 assert fp.erfc(0+0j) == 1 assert ae(fp.erfc(0.3), 0.67137324054087258381) assert ae(fp.erfc(-0.3), 1.3286267594591274162) assert ae(fp.erfc(0.9), 0.20309178757716786034) assert ae(fp.erfc(-0.9), 1.7969082124228321397) assert ae(fp.erfc(1.0), 0.15729920705028513066) assert ae(fp.erfc(-1.0), 1.8427007929497148693) assert ae(fp.erfc(1.1), 0.11979493042591827034) assert ae(fp.erfc(-1.1), 1.8802050695740817297) assert ae(fp.erfc(8.5), 2.7623240713337714461e-33) assert ae(fp.erfc(-8.5), 2.0) assert ae(fp.erfc(9.1), 6.6969004279886077452e-38) assert ae(fp.erfc(-9.1), 2.0) assert ae(fp.erfc(20.0), 5.3958656116079009289e-176) assert ae(fp.erfc(-20.0), 2.0) assert ae(fp.erfc(10000.0), 0.0) assert ae(fp.erfc(-10000.0), 2.0) assert ae(fp.erfc(1e+50), 0.0) assert ae(fp.erfc(-1e+50), 2.0) assert ae(fp.erfc(1j), (1.0 - 1.650425758797542876j)) assert ae(fp.erfc(-1j), (1.0 + 1.650425758797542876j)) assert ae(fp.erfc((2+3j)), (21.829461427614568389 - 8.6873182714701631444j), 1e-13) assert ae(fp.erfc(-(2+3j)), (-19.829461427614568389 + 8.6873182714701631444j), 1e-13) assert ae(fp.erfc((8+9j)), (1072005.2525062051158 - 364149.91954310255423j)) assert ae(fp.erfc(-(8+9j)), (-1072003.2525062051158 + 364149.91954310255423j)) assert ae(fp.erfc(20+0j), (5.3958656116079009289e-176 + 0.0j)) def test_fp_lambertw(): assert ae(fp.lambertw(0.0), 0.0) assert ae(fp.lambertw(1.0), 0.567143290409783873) assert ae(fp.lambertw(7.5), 1.5662309537823875394) assert ae(fp.lambertw(-0.25), -0.35740295618138890307) assert ae(fp.lambertw(-10.0), (1.3699809685212708156 + 2.140194527074713196j)) assert ae(fp.lambertw(0+0j), (0.0 + 0.0j)) assert ae(fp.lambertw(4+0j), (1.2021678731970429392 + 0.0j)) assert ae(fp.lambertw(1000.5), 5.2500227450408980127) assert ae(fp.lambertw(1e100), 224.84310644511850156) assert ae(fp.lambertw(-1000.0), (5.1501630246362515223 + 2.6641981432905204596j)) assert ae(fp.lambertw(1e-10), 9.9999999990000003645e-11) assert ae(fp.lambertw(1e-10j), (1.0000000000000000728e-20 + 1.0000000000000000364e-10j)) assert ae(fp.lambertw(3+4j), (1.2815618061237758782 + 0.53309522202097107131j)) assert ae(fp.lambertw(-3-4j), (1.0750730665692549276 - 1.3251023817343588823j)) assert ae(fp.lambertw(10000+1000j), (7.2361526563371602186 + 0.087567810943839352034j)) assert ae(fp.lambertw(0.0, -1), -fp.inf) assert ae(fp.lambertw(1.0, -1), (-1.5339133197935745079 - 4.3751851530618983855j)) assert ae(fp.lambertw(7.5, -1), (0.44125668415098614999 - 4.8039842008452390179j)) assert ae(fp.lambertw(-0.25, -1), -2.1532923641103496492) assert ae(fp.lambertw(-10.0, -1), (1.3699809685212708156 - 2.140194527074713196j)) assert ae(fp.lambertw(0+0j, -1), -fp.inf) assert ae(fp.lambertw(4+0j, -1), (-0.15730793189620765317 - 4.6787800704666656212j)) assert ae(fp.lambertw(1000.5, -1), (4.9153765415404024736 - 5.4465682700815159569j)) assert ae(fp.lambertw(1e100, -1), (224.84272130101601052 - 6.2553713838167244141j)) assert ae(fp.lambertw(-1000.0, -1), (5.1501630246362515223 - 2.6641981432905204596j)) assert ae(fp.lambertw(1e-10, -1), (-26.303186778379041521 - 3.2650939117038283975j)) assert ae(fp.lambertw(1e-10j, -1), (-26.297238779529035028 - 1.6328071613455765135j)) assert ae(fp.lambertw(3+4j, -1), (0.25856740686699741676 - 3.8521166861614355895j)) assert ae(fp.lambertw(-3-4j, -1), (-0.32028750204310768396 - 6.8801677192091972343j)) assert ae(fp.lambertw(10000+1000j, -1), (7.0255308742285435567 - 5.5177506835734067601j)) assert ae(fp.lambertw(0.0, 2), -fp.inf) assert ae(fp.lambertw(1.0, 2), (-2.4015851048680028842 + 10.776299516115070898j)) assert ae(fp.lambertw(7.5, 2), (-0.38003357962843791529 + 10.960916473368746184j)) assert ae(fp.lambertw(-0.25, 2), (-4.0558735269061511898 + 13.852334658567271386j)) assert ae(fp.lambertw(-10.0, 2), (-0.34479123764318858696 + 14.112740596763592363j)) assert ae(fp.lambertw(0+0j, 2), -fp.inf) assert ae(fp.lambertw(4+0j, 2), (-1.0070343323804262788 + 10.903476551861683082j)) assert ae(fp.lambertw(1000.5, 2), (4.4076185165459395295 + 11.365524591091402177j)) assert ae(fp.lambertw(1e100, 2), (224.84156762724875878 + 12.510785262632255672j)) assert ae(fp.lambertw(-1000.0, 2), (4.1984245610246530756 + 14.420478573754313845j)) assert ae(fp.lambertw(1e-10, 2), (-26.362258095445866488 + 9.7800247407031482519j)) assert ae(fp.lambertw(1e-10j, 2), (-26.384250801683084252 + 11.403535950607739763j)) assert ae(fp.lambertw(3+4j, 2), (-0.86554679943333993562 + 11.849956798331992027j)) assert ae(fp.lambertw(-3-4j, 2), (-0.55792273874679112639 + 8.7173627024159324811j)) assert ae(fp.lambertw(10000+1000j, 2), (6.6223802254585662734 + 11.61348646825020766j)) def test_fp_stress_ei_e1(): # Can be tightened on recent Pythons with more accurate math/cmath ATOL = 1e-13 PTOL = 1e-12 v = fp.e1(1.1641532182693481445e-10) assert ae(v, 22.296641293693077672, tol=ATOL) assert type(v) is float v = fp.e1(0.25) assert ae(v, 1.0442826344437381945, tol=ATOL) assert type(v) is float v = fp.e1(1.0) assert ae(v, 0.21938393439552027368, tol=ATOL) assert type(v) is float v = fp.e1(2.0) assert ae(v, 0.048900510708061119567, tol=ATOL) assert type(v) is float v = fp.e1(5.0) assert ae(v, 0.0011482955912753257973, tol=ATOL) assert type(v) is float v = fp.e1(20.0) assert ae(v, 9.8355252906498816904e-11, tol=ATOL) assert type(v) is float v = fp.e1(30.0) assert ae(v, 3.0215520106888125448e-15, tol=ATOL) assert type(v) is float v = fp.e1(40.0) assert ae(v, 1.0367732614516569722e-19, tol=ATOL) assert type(v) is float v = fp.e1(50.0) assert ae(v, 3.7832640295504590187e-24, tol=ATOL) assert type(v) is float v = fp.e1(80.0) assert ae(v, 2.2285432586884729112e-37, tol=ATOL) assert type(v) is float v = fp.e1((1.1641532182693481445e-10 + 0.0j)) assert ae(v, (22.296641293693077672 + 0.0j), tol=ATOL) assert ae(v.real, 22.296641293693077672, tol=PTOL) assert v.imag == 0 v = fp.e1((0.25 + 0.0j)) assert ae(v, (1.0442826344437381945 + 0.0j), tol=ATOL) assert ae(v.real, 1.0442826344437381945, tol=PTOL) assert v.imag == 0 v = fp.e1((1.0 + 0.0j)) assert ae(v, (0.21938393439552027368 + 0.0j), tol=ATOL) assert ae(v.real, 0.21938393439552027368, tol=PTOL) assert v.imag == 0 v = fp.e1((2.0 + 0.0j)) assert ae(v, (0.048900510708061119567 + 0.0j), tol=ATOL) assert ae(v.real, 0.048900510708061119567, tol=PTOL) assert v.imag == 0 v = fp.e1((5.0 + 0.0j)) assert ae(v, (0.0011482955912753257973 + 0.0j), tol=ATOL) assert ae(v.real, 0.0011482955912753257973, tol=PTOL) assert v.imag == 0 v = fp.e1((20.0 + 0.0j)) assert ae(v, (9.8355252906498816904e-11 + 0.0j), tol=ATOL) assert ae(v.real, 9.8355252906498816904e-11, tol=PTOL) assert v.imag == 0 v = fp.e1((30.0 + 0.0j)) assert ae(v, (3.0215520106888125448e-15 + 0.0j), tol=ATOL) assert ae(v.real, 3.0215520106888125448e-15, tol=PTOL) assert v.imag == 0 v = fp.e1((40.0 + 0.0j)) assert ae(v, (1.0367732614516569722e-19 + 0.0j), tol=ATOL) assert ae(v.real, 1.0367732614516569722e-19, tol=PTOL) assert v.imag == 0 v = fp.e1((50.0 + 0.0j)) assert ae(v, (3.7832640295504590187e-24 + 0.0j), tol=ATOL) assert ae(v.real, 3.7832640295504590187e-24, tol=PTOL) assert v.imag == 0 v = fp.e1((80.0 + 0.0j)) assert ae(v, (2.2285432586884729112e-37 + 0.0j), tol=ATOL) assert ae(v.real, 2.2285432586884729112e-37, tol=PTOL) assert v.imag == 0 v = fp.e1((4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) assert ae(v, (20.880034622014215597 - 0.24497866301044883237j), tol=ATOL) assert ae(v.real, 20.880034622014215597, tol=PTOL) assert ae(v.imag, -0.24497866301044883237, tol=PTOL) v = fp.e1((1.0 + 0.25j)) assert ae(v, (0.19731063945004229095 - 0.087366045774299963672j), tol=ATOL) assert ae(v.real, 0.19731063945004229095, tol=PTOL) assert ae(v.imag, -0.087366045774299963672, tol=PTOL) v = fp.e1((4.0 + 1.0j)) assert ae(v, (0.0013106173980145506944 - 0.0034542480199350626699j), tol=ATOL) assert ae(v.real, 0.0013106173980145506944, tol=PTOL) assert ae(v.imag, -0.0034542480199350626699, tol=PTOL) v = fp.e1((8.0 + 2.0j)) assert ae(v, (-0.000022278049065270225945 - 0.000029191940456521555288j), tol=ATOL) assert ae(v.real, -0.000022278049065270225945, tol=PTOL) assert ae(v.imag, -0.000029191940456521555288, tol=PTOL) v = fp.e1((20.0 + 5.0j)) assert ae(v, (4.7711374515765346894e-11 + 8.2902652405126947359e-11j), tol=ATOL) assert ae(v.real, 4.7711374515765346894e-11, tol=PTOL) assert ae(v.imag, 8.2902652405126947359e-11, tol=PTOL) v = fp.e1((80.0 + 20.0j)) assert ae(v, (3.8353473865788235787e-38 - 2.129247592349605139e-37j), tol=ATOL) assert ae(v.real, 3.8353473865788235787e-38, tol=PTOL) assert ae(v.imag, -2.129247592349605139e-37, tol=PTOL) v = fp.e1((120.0 + 30.0j)) assert ae(v, (2.3836002337480334716e-55 + 5.6704043587126198306e-55j), tol=ATOL) assert ae(v.real, 2.3836002337480334716e-55, tol=PTOL) assert ae(v.imag, 5.6704043587126198306e-55, tol=PTOL) v = fp.e1((160.0 + 40.0j)) assert ae(v, (-1.6238022898654510661e-72 - 1.104172355572287367e-72j), tol=ATOL) assert ae(v.real, -1.6238022898654510661e-72, tol=PTOL) assert ae(v.imag, -1.104172355572287367e-72, tol=PTOL) v = fp.e1((200.0 + 50.0j)) assert ae(v, (6.6800061461666228487e-90 + 1.4473816083541016115e-91j), tol=ATOL) assert ae(v.real, 6.6800061461666228487e-90, tol=PTOL) assert ae(v.imag, 1.4473816083541016115e-91, tol=PTOL) v = fp.e1((320.0 + 80.0j)) assert ae(v, (4.2737871527778786157e-143 + 3.1789935525785660314e-142j), tol=ATOL) assert ae(v.real, 4.2737871527778786157e-143, tol=PTOL) assert ae(v.imag, 3.1789935525785660314e-142, tol=PTOL) v = fp.e1((1.1641532182693481445e-10 + 1.1641532182693481445e-10j)) assert ae(v, (21.950067703413105017 - 0.7853981632810329878j), tol=ATOL) assert ae(v.real, 21.950067703413105017, tol=PTOL) assert ae(v.imag, -0.7853981632810329878, tol=PTOL) v = fp.e1((0.25 + 0.25j)) assert ae(v, (0.71092525792923287894 - 0.56491812441304194711j), tol=ATOL) assert ae(v.real, 0.71092525792923287894, tol=PTOL) assert ae(v.imag, -0.56491812441304194711, tol=PTOL) v = fp.e1((1.0 + 1.0j)) assert ae(v, (0.00028162445198141832551 - 0.17932453503935894015j), tol=ATOL) assert ae(v.real, 0.00028162445198141832551, tol=PTOL) assert ae(v.imag, -0.17932453503935894015, tol=PTOL) v = fp.e1((2.0 + 2.0j)) assert ae(v, (-0.033767089606562004246 - 0.018599414169750541925j), tol=ATOL) assert ae(v.real, -0.033767089606562004246, tol=PTOL) assert ae(v.imag, -0.018599414169750541925, tol=PTOL) v = fp.e1((5.0 + 5.0j)) assert ae(v, (0.0007266506660356393891 + 0.00047102780163522245054j), tol=ATOL) assert ae(v.real, 0.0007266506660356393891, tol=PTOL) assert ae(v.imag, 0.00047102780163522245054, tol=PTOL) v = fp.e1((20.0 + 20.0j)) assert ae(v, (-2.3824537449367396579e-11 - 6.6969873156525615158e-11j), tol=ATOL) assert ae(v.real, -2.3824537449367396579e-11, tol=PTOL) assert ae(v.imag, -6.6969873156525615158e-11, tol=PTOL) v = fp.e1((30.0 + 30.0j)) assert ae(v, (1.7316045841744061617e-15 + 1.3065678019487308689e-15j), tol=ATOL) assert ae(v.real, 1.7316045841744061617e-15, tol=PTOL) assert ae(v.imag, 1.3065678019487308689e-15, tol=PTOL) v = fp.e1((40.0 + 40.0j)) assert ae(v, (-7.4001043002899232182e-20 - 4.991847855336816304e-21j), tol=ATOL) assert ae(v.real, -7.4001043002899232182e-20, tol=PTOL) assert ae(v.imag, -4.991847855336816304e-21, tol=PTOL) v = fp.e1((50.0 + 50.0j)) assert ae(v, (2.3566128324644641219e-24 - 1.3188326726201614778e-24j), tol=ATOL) assert ae(v.real, 2.3566128324644641219e-24, tol=PTOL) assert ae(v.imag, -1.3188326726201614778e-24, tol=PTOL) v = fp.e1((80.0 + 80.0j)) assert ae(v, (9.8279750572186526673e-38 + 1.243952841288868831e-37j), tol=ATOL) assert ae(v.real, 9.8279750572186526673e-38, tol=PTOL) assert ae(v.imag, 1.243952841288868831e-37, tol=PTOL) v = fp.e1((1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) assert ae(v, (20.880034621664969632 - 1.3258176632023711778j), tol=ATOL) assert ae(v.real, 20.880034621664969632, tol=PTOL) assert ae(v.imag, -1.3258176632023711778, tol=PTOL) v = fp.e1((0.25 + 1.0j)) assert ae(v, (-0.16868306393667788761 - 0.4858011885947426971j), tol=ATOL) assert ae(v.real, -0.16868306393667788761, tol=PTOL) assert ae(v.imag, -0.4858011885947426971, tol=PTOL) v = fp.e1((1.0 + 4.0j)) assert ae(v, (0.03373591813926547318 + 0.073523452241083821877j), tol=ATOL) assert ae(v.real, 0.03373591813926547318, tol=PTOL) assert ae(v.imag, 0.073523452241083821877, tol=PTOL) v = fp.e1((2.0 + 8.0j)) assert ae(v, (-0.015392833434733785143 - 0.0031747121557605415914j), tol=ATOL) assert ae(v.real, -0.015392833434733785143, tol=PTOL) assert ae(v.imag, -0.0031747121557605415914, tol=PTOL) v = fp.e1((5.0 + 20.0j)) assert ae(v, (-0.00024419662286542966525 - 0.00021008322966152755674j), tol=ATOL) assert ae(v.real, -0.00024419662286542966525, tol=PTOL) assert ae(v.imag, -0.00021008322966152755674, tol=PTOL) v = fp.e1((20.0 + 80.0j)) assert ae(v, (2.3255552781051330088e-11 + 8.9463918891349438007e-12j), tol=ATOL) assert ae(v.real, 2.3255552781051330088e-11, tol=PTOL) assert ae(v.imag, 8.9463918891349438007e-12, tol=PTOL) v = fp.e1((30.0 + 120.0j)) assert ae(v, (-2.7068919097124652332e-16 - 7.0477762411705130239e-16j), tol=ATOL) assert ae(v.real, -2.7068919097124652332e-16, tol=PTOL) assert ae(v.imag, -7.0477762411705130239e-16, tol=PTOL) v = fp.e1((40.0 + 160.0j)) assert ae(v, (-1.1695597827678024687e-20 + 2.2907401455645736661e-20j), tol=ATOL) assert ae(v.real, -1.1695597827678024687e-20, tol=PTOL) assert ae(v.imag, 2.2907401455645736661e-20, tol=PTOL) v = fp.e1((50.0 + 200.0j)) assert ae(v, (9.0323746914410162531e-25 - 2.3950601790033530935e-25j), tol=ATOL) assert ae(v.real, 9.0323746914410162531e-25, tol=PTOL) assert ae(v.imag, -2.3950601790033530935e-25, tol=PTOL) v = fp.e1((80.0 + 320.0j)) assert ae(v, (3.4819106748728063576e-38 - 4.215653005615772724e-38j), tol=ATOL) assert ae(v.real, 3.4819106748728063576e-38, tol=PTOL) assert ae(v.imag, -4.215653005615772724e-38, tol=PTOL) v = fp.e1((0.0 + 1.1641532182693481445e-10j)) assert ae(v, (22.29664129357666235 - 1.5707963266784812974j), tol=ATOL) assert ae(v.real, 22.29664129357666235, tol=PTOL) assert ae(v.imag, -1.5707963266784812974, tol=PTOL) v = fp.e1((0.0 + 0.25j)) assert ae(v, (0.82466306258094565309 - 1.3216627564751394551j), tol=ATOL) assert ae(v.real, 0.82466306258094565309, tol=PTOL) assert ae(v.imag, -1.3216627564751394551, tol=PTOL) v = fp.e1((0.0 + 1.0j)) assert ae(v, (-0.33740392290096813466 - 0.62471325642771360429j), tol=ATOL) assert ae(v.real, -0.33740392290096813466, tol=PTOL) assert ae(v.imag, -0.62471325642771360429, tol=PTOL) v = fp.e1((0.0 + 2.0j)) assert ae(v, (-0.4229808287748649957 + 0.034616650007798229345j), tol=ATOL) assert ae(v.real, -0.4229808287748649957, tol=PTOL) assert ae(v.imag, 0.034616650007798229345, tol=PTOL) v = fp.e1((0.0 + 5.0j)) assert ae(v, (0.19002974965664387862 - 0.020865081850222481957j), tol=ATOL) assert ae(v.real, 0.19002974965664387862, tol=PTOL) assert ae(v.imag, -0.020865081850222481957, tol=PTOL) v = fp.e1((0.0 + 20.0j)) assert ae(v, (-0.04441982084535331654 - 0.022554625751456779068j), tol=ATOL) assert ae(v.real, -0.04441982084535331654, tol=PTOL) assert ae(v.imag, -0.022554625751456779068, tol=PTOL) v = fp.e1((0.0 + 30.0j)) assert ae(v, (0.033032417282071143779 - 0.0040397867645455082476j), tol=ATOL) assert ae(v.real, 0.033032417282071143779, tol=PTOL) assert ae(v.imag, -0.0040397867645455082476, tol=PTOL) v = fp.e1((0.0 + 40.0j)) assert ae(v, (-0.019020007896208766962 + 0.016188792559887887544j), tol=ATOL) assert ae(v.real, -0.019020007896208766962, tol=PTOL) assert ae(v.imag, 0.016188792559887887544, tol=PTOL) v = fp.e1((0.0 + 50.0j)) assert ae(v, (0.0056283863241163054402 - 0.019179254308960724503j), tol=ATOL) assert ae(v.real, 0.0056283863241163054402, tol=PTOL) assert ae(v.imag, -0.019179254308960724503, tol=PTOL) v = fp.e1((0.0 + 80.0j)) assert ae(v, (0.012402501155070958192 + 0.0015345601175906961199j), tol=ATOL) assert ae(v.real, 0.012402501155070958192, tol=PTOL) assert ae(v.imag, 0.0015345601175906961199, tol=PTOL) v = fp.e1((-1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) assert ae(v, (20.880034621432138988 - 1.8157749894560994861j), tol=ATOL) assert ae(v.real, 20.880034621432138988, tol=PTOL) assert ae(v.imag, -1.8157749894560994861, tol=PTOL) v = fp.e1((-0.25 + 1.0j)) assert ae(v, (-0.59066621214766308594 - 0.74474454765205036972j), tol=ATOL) assert ae(v.real, -0.59066621214766308594, tol=PTOL) assert ae(v.imag, -0.74474454765205036972, tol=PTOL) v = fp.e1((-1.0 + 4.0j)) assert ae(v, (0.49739047283060471093 + 0.41543605404038863174j), tol=ATOL) assert ae(v.real, 0.49739047283060471093, tol=PTOL) assert ae(v.imag, 0.41543605404038863174, tol=PTOL) v = fp.e1((-2.0 + 8.0j)) assert ae(v, (-0.8705211147733730969 + 0.24099328498605539667j), tol=ATOL) assert ae(v.real, -0.8705211147733730969, tol=PTOL) assert ae(v.imag, 0.24099328498605539667, tol=PTOL) v = fp.e1((-5.0 + 20.0j)) assert ae(v, (-7.0789514293925893007 - 1.6102177171960790536j), tol=ATOL) assert ae(v.real, -7.0789514293925893007, tol=PTOL) assert ae(v.imag, -1.6102177171960790536, tol=PTOL) v = fp.e1((-20.0 + 80.0j)) assert ae(v, (5855431.4907298084434 - 720920.93315409165707j), tol=ATOL) assert ae(v.real, 5855431.4907298084434, tol=PTOL) assert ae(v.imag, -720920.93315409165707, tol=PTOL) v = fp.e1((-30.0 + 120.0j)) assert ae(v, (-65402491644.703470747 - 56697658399.657460294j), tol=ATOL) assert ae(v.real, -65402491644.703470747, tol=PTOL) assert ae(v.imag, -56697658399.657460294, tol=PTOL) v = fp.e1((-40.0 + 160.0j)) assert ae(v, (25504929379604.776769 + 1429035198630573.2463j), tol=ATOL) assert ae(v.real, 25504929379604.776769, tol=PTOL) assert ae(v.imag, 1429035198630573.2463, tol=PTOL) v = fp.e1((-50.0 + 200.0j)) assert ae(v, (18437746526988116954.0 - 17146362239046152345.0j), tol=ATOL) assert ae(v.real, 18437746526988116954.0, tol=PTOL) assert ae(v.imag, -17146362239046152345.0, tol=PTOL) v = fp.e1((-80.0 + 320.0j)) assert ae(v, (3.3464697299634526706e+31 - 1.6473152633843023919e+32j), tol=ATOL) assert ae(v.real, 3.3464697299634526706e+31, tol=PTOL) assert ae(v.imag, -1.6473152633843023919e+32, tol=PTOL) v = fp.e1((-4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) assert ae(v, (20.880034621082893023 - 2.8966139903465137624j), tol=ATOL) assert ae(v.real, 20.880034621082893023, tol=PTOL) assert ae(v.imag, -2.8966139903465137624, tol=PTOL) v = fp.e1((-1.0 + 0.25j)) assert ae(v, (-1.8942716983721074932 - 2.4689102827070540799j), tol=ATOL) assert ae(v.real, -1.8942716983721074932, tol=PTOL) assert ae(v.imag, -2.4689102827070540799, tol=PTOL) v = fp.e1((-4.0 + 1.0j)) assert ae(v, (-14.806699492675420438 + 9.1384225230837893776j), tol=ATOL) assert ae(v.real, -14.806699492675420438, tol=PTOL) assert ae(v.imag, 9.1384225230837893776, tol=PTOL) v = fp.e1((-8.0 + 2.0j)) assert ae(v, (54.633252667426386294 + 413.20318163814670688j), tol=ATOL) assert ae(v.real, 54.633252667426386294, tol=PTOL) assert ae(v.imag, 413.20318163814670688, tol=PTOL) v = fp.e1((-20.0 + 5.0j)) assert ae(v, (-711836.97165402624643 - 24745250.939695900956j), tol=ATOL) assert ae(v.real, -711836.97165402624643, tol=PTOL) assert ae(v.imag, -24745250.939695900956, tol=PTOL) v = fp.e1((-80.0 + 20.0j)) assert ae(v, (-4.2139911108612653091e+32 + 5.3367124741918251637e+32j), tol=ATOL) assert ae(v.real, -4.2139911108612653091e+32, tol=PTOL) assert ae(v.imag, 5.3367124741918251637e+32, tol=PTOL) v = fp.e1((-120.0 + 30.0j)) assert ae(v, (9.7760616203707508892e+48 - 1.058257682317195792e+50j), tol=ATOL) assert ae(v.real, 9.7760616203707508892e+48, tol=PTOL) assert ae(v.imag, -1.058257682317195792e+50, tol=PTOL) v = fp.e1((-160.0 + 40.0j)) assert ae(v, (8.7065541466623638861e+66 + 1.6577106725141739889e+67j), tol=ATOL) assert ae(v.real, 8.7065541466623638861e+66, tol=PTOL) assert ae(v.imag, 1.6577106725141739889e+67, tol=PTOL) v = fp.e1((-200.0 + 50.0j)) assert ae(v, (-3.070744996327018106e+84 - 1.7243244846769415903e+84j), tol=ATOL) assert ae(v.real, -3.070744996327018106e+84, tol=PTOL) assert ae(v.imag, -1.7243244846769415903e+84, tol=PTOL) v = fp.e1((-320.0 + 80.0j)) assert ae(v, (9.9960598637998647276e+135 - 2.6855081527595608863e+136j), tol=ATOL) assert ae(v.real, 9.9960598637998647276e+135, tol=PTOL) assert ae(v.imag, -2.6855081527595608863e+136, tol=PTOL) v = fp.e1(-1.1641532182693481445e-10) assert ae(v, (22.296641293460247028 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, 22.296641293460247028, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1(-0.25) assert ae(v, (0.54254326466191372953 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, 0.54254326466191372953, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1(-1.0) assert ae(v, (-1.8951178163559367555 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -1.8951178163559367555, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1(-2.0) assert ae(v, (-4.9542343560018901634 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -4.9542343560018901634, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1(-5.0) assert ae(v, (-40.185275355803177455 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -40.185275355803177455, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1(-20.0) assert ae(v, (-25615652.66405658882 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -25615652.66405658882, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1(-30.0) assert ae(v, (-368973209407.27419706 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -368973209407.27419706, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1(-40.0) assert ae(v, (-6039718263611241.5784 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -6039718263611241.5784, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1(-50.0) assert ae(v, (-1.0585636897131690963e+20 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -1.0585636897131690963e+20, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1(-80.0) assert ae(v, (-7.0146000049047999696e+32 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -7.0146000049047999696e+32, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-1.1641532182693481445e-10 + 0.0j)) assert ae(v, (22.296641293460247028 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, 22.296641293460247028, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-0.25 + 0.0j)) assert ae(v, (0.54254326466191372953 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, 0.54254326466191372953, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-1.0 + 0.0j)) assert ae(v, (-1.8951178163559367555 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -1.8951178163559367555, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-2.0 + 0.0j)) assert ae(v, (-4.9542343560018901634 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -4.9542343560018901634, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-5.0 + 0.0j)) assert ae(v, (-40.185275355803177455 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -40.185275355803177455, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-20.0 + 0.0j)) assert ae(v, (-25615652.66405658882 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -25615652.66405658882, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-30.0 + 0.0j)) assert ae(v, (-368973209407.27419706 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -368973209407.27419706, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-40.0 + 0.0j)) assert ae(v, (-6039718263611241.5784 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -6039718263611241.5784, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-50.0 + 0.0j)) assert ae(v, (-1.0585636897131690963e+20 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -1.0585636897131690963e+20, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-80.0 + 0.0j)) assert ae(v, (-7.0146000049047999696e+32 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -7.0146000049047999696e+32, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.e1((-4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) assert ae(v, (20.880034621082893023 + 2.8966139903465137624j), tol=ATOL) assert ae(v.real, 20.880034621082893023, tol=PTOL) assert ae(v.imag, 2.8966139903465137624, tol=PTOL) v = fp.e1((-1.0 - 0.25j)) assert ae(v, (-1.8942716983721074932 + 2.4689102827070540799j), tol=ATOL) assert ae(v.real, -1.8942716983721074932, tol=PTOL) assert ae(v.imag, 2.4689102827070540799, tol=PTOL) v = fp.e1((-4.0 - 1.0j)) assert ae(v, (-14.806699492675420438 - 9.1384225230837893776j), tol=ATOL) assert ae(v.real, -14.806699492675420438, tol=PTOL) assert ae(v.imag, -9.1384225230837893776, tol=PTOL) v = fp.e1((-8.0 - 2.0j)) assert ae(v, (54.633252667426386294 - 413.20318163814670688j), tol=ATOL) assert ae(v.real, 54.633252667426386294, tol=PTOL) assert ae(v.imag, -413.20318163814670688, tol=PTOL) v = fp.e1((-20.0 - 5.0j)) assert ae(v, (-711836.97165402624643 + 24745250.939695900956j), tol=ATOL) assert ae(v.real, -711836.97165402624643, tol=PTOL) assert ae(v.imag, 24745250.939695900956, tol=PTOL) v = fp.e1((-80.0 - 20.0j)) assert ae(v, (-4.2139911108612653091e+32 - 5.3367124741918251637e+32j), tol=ATOL) assert ae(v.real, -4.2139911108612653091e+32, tol=PTOL) assert ae(v.imag, -5.3367124741918251637e+32, tol=PTOL) v = fp.e1((-120.0 - 30.0j)) assert ae(v, (9.7760616203707508892e+48 + 1.058257682317195792e+50j), tol=ATOL) assert ae(v.real, 9.7760616203707508892e+48, tol=PTOL) assert ae(v.imag, 1.058257682317195792e+50, tol=PTOL) v = fp.e1((-160.0 - 40.0j)) assert ae(v, (8.7065541466623638861e+66 - 1.6577106725141739889e+67j), tol=ATOL) assert ae(v.real, 8.7065541466623638861e+66, tol=PTOL) assert ae(v.imag, -1.6577106725141739889e+67, tol=PTOL) v = fp.e1((-200.0 - 50.0j)) assert ae(v, (-3.070744996327018106e+84 + 1.7243244846769415903e+84j), tol=ATOL) assert ae(v.real, -3.070744996327018106e+84, tol=PTOL) assert ae(v.imag, 1.7243244846769415903e+84, tol=PTOL) v = fp.e1((-320.0 - 80.0j)) assert ae(v, (9.9960598637998647276e+135 + 2.6855081527595608863e+136j), tol=ATOL) assert ae(v.real, 9.9960598637998647276e+135, tol=PTOL) assert ae(v.imag, 2.6855081527595608863e+136, tol=PTOL) v = fp.e1((-1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) assert ae(v, (21.950067703180274374 + 2.356194490075929607j), tol=ATOL) assert ae(v.real, 21.950067703180274374, tol=PTOL) assert ae(v.imag, 2.356194490075929607, tol=PTOL) v = fp.e1((-0.25 - 0.25j)) assert ae(v, (0.21441047326710323254 + 2.0732153554307936389j), tol=ATOL) assert ae(v.real, 0.21441047326710323254, tol=PTOL) assert ae(v.imag, 2.0732153554307936389, tol=PTOL) v = fp.e1((-1.0 - 1.0j)) assert ae(v, (-1.7646259855638540684 + 0.7538228020792708192j), tol=ATOL) assert ae(v.real, -1.7646259855638540684, tol=PTOL) assert ae(v.imag, 0.7538228020792708192, tol=PTOL) v = fp.e1((-2.0 - 2.0j)) assert ae(v, (-1.8920781621855474089 - 2.1753697842428647236j), tol=ATOL) assert ae(v.real, -1.8920781621855474089, tol=PTOL) assert ae(v.imag, -2.1753697842428647236, tol=PTOL) v = fp.e1((-5.0 - 5.0j)) assert ae(v, (13.470936071475245856 + 18.464085049321024206j), tol=ATOL) assert ae(v.real, 13.470936071475245856, tol=PTOL) assert ae(v.imag, 18.464085049321024206, tol=PTOL) v = fp.e1((-20.0 - 20.0j)) assert ae(v, (-16589317.398788971896 - 5831702.3296441771206j), tol=ATOL) assert ae(v.real, -16589317.398788971896, tol=PTOL) assert ae(v.imag, -5831702.3296441771206, tol=PTOL) v = fp.e1((-30.0 - 30.0j)) assert ae(v, (154596484273.69322527 + 204179357837.41389696j), tol=ATOL) assert ae(v.real, 154596484273.69322527, tol=PTOL) assert ae(v.imag, 204179357837.41389696, tol=PTOL) v = fp.e1((-40.0 - 40.0j)) assert ae(v, (-287512180321448.45408 - 4203502407932314.974j), tol=ATOL) assert ae(v.real, -287512180321448.45408, tol=PTOL) assert ae(v.imag, -4203502407932314.974, tol=PTOL) v = fp.e1((-50.0 - 50.0j)) assert ae(v, (-36128528616649268826.0 + 64648801861338741963.0j), tol=ATOL) assert ae(v.real, -36128528616649268826.0, tol=PTOL) assert ae(v.imag, 64648801861338741963.0, tol=PTOL) v = fp.e1((-80.0 - 80.0j)) assert ae(v, (3.8674816337930010217e+32 + 3.0540709639658071041e+32j), tol=ATOL) assert ae(v.real, 3.8674816337930010217e+32, tol=PTOL) assert ae(v.imag, 3.0540709639658071041e+32, tol=PTOL) v = fp.e1((-1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) assert ae(v, (20.880034621432138988 + 1.8157749894560994861j), tol=ATOL) assert ae(v.real, 20.880034621432138988, tol=PTOL) assert ae(v.imag, 1.8157749894560994861, tol=PTOL) v = fp.e1((-0.25 - 1.0j)) assert ae(v, (-0.59066621214766308594 + 0.74474454765205036972j), tol=ATOL) assert ae(v.real, -0.59066621214766308594, tol=PTOL) assert ae(v.imag, 0.74474454765205036972, tol=PTOL) v = fp.e1((-1.0 - 4.0j)) assert ae(v, (0.49739047283060471093 - 0.41543605404038863174j), tol=ATOL) assert ae(v.real, 0.49739047283060471093, tol=PTOL) assert ae(v.imag, -0.41543605404038863174, tol=PTOL) v = fp.e1((-2.0 - 8.0j)) assert ae(v, (-0.8705211147733730969 - 0.24099328498605539667j), tol=ATOL) assert ae(v.real, -0.8705211147733730969, tol=PTOL) assert ae(v.imag, -0.24099328498605539667, tol=PTOL) v = fp.e1((-5.0 - 20.0j)) assert ae(v, (-7.0789514293925893007 + 1.6102177171960790536j), tol=ATOL) assert ae(v.real, -7.0789514293925893007, tol=PTOL) assert ae(v.imag, 1.6102177171960790536, tol=PTOL) v = fp.e1((-20.0 - 80.0j)) assert ae(v, (5855431.4907298084434 + 720920.93315409165707j), tol=ATOL) assert ae(v.real, 5855431.4907298084434, tol=PTOL) assert ae(v.imag, 720920.93315409165707, tol=PTOL) v = fp.e1((-30.0 - 120.0j)) assert ae(v, (-65402491644.703470747 + 56697658399.657460294j), tol=ATOL) assert ae(v.real, -65402491644.703470747, tol=PTOL) assert ae(v.imag, 56697658399.657460294, tol=PTOL) v = fp.e1((-40.0 - 160.0j)) assert ae(v, (25504929379604.776769 - 1429035198630573.2463j), tol=ATOL) assert ae(v.real, 25504929379604.776769, tol=PTOL) assert ae(v.imag, -1429035198630573.2463, tol=PTOL) v = fp.e1((-50.0 - 200.0j)) assert ae(v, (18437746526988116954.0 + 17146362239046152345.0j), tol=ATOL) assert ae(v.real, 18437746526988116954.0, tol=PTOL) assert ae(v.imag, 17146362239046152345.0, tol=PTOL) v = fp.e1((-80.0 - 320.0j)) assert ae(v, (3.3464697299634526706e+31 + 1.6473152633843023919e+32j), tol=ATOL) assert ae(v.real, 3.3464697299634526706e+31, tol=PTOL) assert ae(v.imag, 1.6473152633843023919e+32, tol=PTOL) v = fp.e1((0.0 - 1.1641532182693481445e-10j)) assert ae(v, (22.29664129357666235 + 1.5707963266784812974j), tol=ATOL) assert ae(v.real, 22.29664129357666235, tol=PTOL) assert ae(v.imag, 1.5707963266784812974, tol=PTOL) v = fp.e1((0.0 - 0.25j)) assert ae(v, (0.82466306258094565309 + 1.3216627564751394551j), tol=ATOL) assert ae(v.real, 0.82466306258094565309, tol=PTOL) assert ae(v.imag, 1.3216627564751394551, tol=PTOL) v = fp.e1((0.0 - 1.0j)) assert ae(v, (-0.33740392290096813466 + 0.62471325642771360429j), tol=ATOL) assert ae(v.real, -0.33740392290096813466, tol=PTOL) assert ae(v.imag, 0.62471325642771360429, tol=PTOL) v = fp.e1((0.0 - 2.0j)) assert ae(v, (-0.4229808287748649957 - 0.034616650007798229345j), tol=ATOL) assert ae(v.real, -0.4229808287748649957, tol=PTOL) assert ae(v.imag, -0.034616650007798229345, tol=PTOL) v = fp.e1((0.0 - 5.0j)) assert ae(v, (0.19002974965664387862 + 0.020865081850222481957j), tol=ATOL) assert ae(v.real, 0.19002974965664387862, tol=PTOL) assert ae(v.imag, 0.020865081850222481957, tol=PTOL) v = fp.e1((0.0 - 20.0j)) assert ae(v, (-0.04441982084535331654 + 0.022554625751456779068j), tol=ATOL) assert ae(v.real, -0.04441982084535331654, tol=PTOL) assert ae(v.imag, 0.022554625751456779068, tol=PTOL) v = fp.e1((0.0 - 30.0j)) assert ae(v, (0.033032417282071143779 + 0.0040397867645455082476j), tol=ATOL) assert ae(v.real, 0.033032417282071143779, tol=PTOL) assert ae(v.imag, 0.0040397867645455082476, tol=PTOL) v = fp.e1((0.0 - 40.0j)) assert ae(v, (-0.019020007896208766962 - 0.016188792559887887544j), tol=ATOL) assert ae(v.real, -0.019020007896208766962, tol=PTOL) assert ae(v.imag, -0.016188792559887887544, tol=PTOL) v = fp.e1((0.0 - 50.0j)) assert ae(v, (0.0056283863241163054402 + 0.019179254308960724503j), tol=ATOL) assert ae(v.real, 0.0056283863241163054402, tol=PTOL) assert ae(v.imag, 0.019179254308960724503, tol=PTOL) v = fp.e1((0.0 - 80.0j)) assert ae(v, (0.012402501155070958192 - 0.0015345601175906961199j), tol=ATOL) assert ae(v.real, 0.012402501155070958192, tol=PTOL) assert ae(v.imag, -0.0015345601175906961199, tol=PTOL) v = fp.e1((1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) assert ae(v, (20.880034621664969632 + 1.3258176632023711778j), tol=ATOL) assert ae(v.real, 20.880034621664969632, tol=PTOL) assert ae(v.imag, 1.3258176632023711778, tol=PTOL) v = fp.e1((0.25 - 1.0j)) assert ae(v, (-0.16868306393667788761 + 0.4858011885947426971j), tol=ATOL) assert ae(v.real, -0.16868306393667788761, tol=PTOL) assert ae(v.imag, 0.4858011885947426971, tol=PTOL) v = fp.e1((1.0 - 4.0j)) assert ae(v, (0.03373591813926547318 - 0.073523452241083821877j), tol=ATOL) assert ae(v.real, 0.03373591813926547318, tol=PTOL) assert ae(v.imag, -0.073523452241083821877, tol=PTOL) v = fp.e1((2.0 - 8.0j)) assert ae(v, (-0.015392833434733785143 + 0.0031747121557605415914j), tol=ATOL) assert ae(v.real, -0.015392833434733785143, tol=PTOL) assert ae(v.imag, 0.0031747121557605415914, tol=PTOL) v = fp.e1((5.0 - 20.0j)) assert ae(v, (-0.00024419662286542966525 + 0.00021008322966152755674j), tol=ATOL) assert ae(v.real, -0.00024419662286542966525, tol=PTOL) assert ae(v.imag, 0.00021008322966152755674, tol=PTOL) v = fp.e1((20.0 - 80.0j)) assert ae(v, (2.3255552781051330088e-11 - 8.9463918891349438007e-12j), tol=ATOL) assert ae(v.real, 2.3255552781051330088e-11, tol=PTOL) assert ae(v.imag, -8.9463918891349438007e-12, tol=PTOL) v = fp.e1((30.0 - 120.0j)) assert ae(v, (-2.7068919097124652332e-16 + 7.0477762411705130239e-16j), tol=ATOL) assert ae(v.real, -2.7068919097124652332e-16, tol=PTOL) assert ae(v.imag, 7.0477762411705130239e-16, tol=PTOL) v = fp.e1((40.0 - 160.0j)) assert ae(v, (-1.1695597827678024687e-20 - 2.2907401455645736661e-20j), tol=ATOL) assert ae(v.real, -1.1695597827678024687e-20, tol=PTOL) assert ae(v.imag, -2.2907401455645736661e-20, tol=PTOL) v = fp.e1((50.0 - 200.0j)) assert ae(v, (9.0323746914410162531e-25 + 2.3950601790033530935e-25j), tol=ATOL) assert ae(v.real, 9.0323746914410162531e-25, tol=PTOL) assert ae(v.imag, 2.3950601790033530935e-25, tol=PTOL) v = fp.e1((80.0 - 320.0j)) assert ae(v, (3.4819106748728063576e-38 + 4.215653005615772724e-38j), tol=ATOL) assert ae(v.real, 3.4819106748728063576e-38, tol=PTOL) assert ae(v.imag, 4.215653005615772724e-38, tol=PTOL) v = fp.e1((1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) assert ae(v, (21.950067703413105017 + 0.7853981632810329878j), tol=ATOL) assert ae(v.real, 21.950067703413105017, tol=PTOL) assert ae(v.imag, 0.7853981632810329878, tol=PTOL) v = fp.e1((0.25 - 0.25j)) assert ae(v, (0.71092525792923287894 + 0.56491812441304194711j), tol=ATOL) assert ae(v.real, 0.71092525792923287894, tol=PTOL) assert ae(v.imag, 0.56491812441304194711, tol=PTOL) v = fp.e1((1.0 - 1.0j)) assert ae(v, (0.00028162445198141832551 + 0.17932453503935894015j), tol=ATOL) assert ae(v.real, 0.00028162445198141832551, tol=PTOL) assert ae(v.imag, 0.17932453503935894015, tol=PTOL) v = fp.e1((2.0 - 2.0j)) assert ae(v, (-0.033767089606562004246 + 0.018599414169750541925j), tol=ATOL) assert ae(v.real, -0.033767089606562004246, tol=PTOL) assert ae(v.imag, 0.018599414169750541925, tol=PTOL) v = fp.e1((5.0 - 5.0j)) assert ae(v, (0.0007266506660356393891 - 0.00047102780163522245054j), tol=ATOL) assert ae(v.real, 0.0007266506660356393891, tol=PTOL) assert ae(v.imag, -0.00047102780163522245054, tol=PTOL) v = fp.e1((20.0 - 20.0j)) assert ae(v, (-2.3824537449367396579e-11 + 6.6969873156525615158e-11j), tol=ATOL) assert ae(v.real, -2.3824537449367396579e-11, tol=PTOL) assert ae(v.imag, 6.6969873156525615158e-11, tol=PTOL) v = fp.e1((30.0 - 30.0j)) assert ae(v, (1.7316045841744061617e-15 - 1.3065678019487308689e-15j), tol=ATOL) assert ae(v.real, 1.7316045841744061617e-15, tol=PTOL) assert ae(v.imag, -1.3065678019487308689e-15, tol=PTOL) v = fp.e1((40.0 - 40.0j)) assert ae(v, (-7.4001043002899232182e-20 + 4.991847855336816304e-21j), tol=ATOL) assert ae(v.real, -7.4001043002899232182e-20, tol=PTOL) assert ae(v.imag, 4.991847855336816304e-21, tol=PTOL) v = fp.e1((50.0 - 50.0j)) assert ae(v, (2.3566128324644641219e-24 + 1.3188326726201614778e-24j), tol=ATOL) assert ae(v.real, 2.3566128324644641219e-24, tol=PTOL) assert ae(v.imag, 1.3188326726201614778e-24, tol=PTOL) v = fp.e1((80.0 - 80.0j)) assert ae(v, (9.8279750572186526673e-38 - 1.243952841288868831e-37j), tol=ATOL) assert ae(v.real, 9.8279750572186526673e-38, tol=PTOL) assert ae(v.imag, -1.243952841288868831e-37, tol=PTOL) v = fp.e1((4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) assert ae(v, (20.880034622014215597 + 0.24497866301044883237j), tol=ATOL) assert ae(v.real, 20.880034622014215597, tol=PTOL) assert ae(v.imag, 0.24497866301044883237, tol=PTOL) v = fp.e1((1.0 - 0.25j)) assert ae(v, (0.19731063945004229095 + 0.087366045774299963672j), tol=ATOL) assert ae(v.real, 0.19731063945004229095, tol=PTOL) assert ae(v.imag, 0.087366045774299963672, tol=PTOL) v = fp.e1((4.0 - 1.0j)) assert ae(v, (0.0013106173980145506944 + 0.0034542480199350626699j), tol=ATOL) assert ae(v.real, 0.0013106173980145506944, tol=PTOL) assert ae(v.imag, 0.0034542480199350626699, tol=PTOL) v = fp.e1((8.0 - 2.0j)) assert ae(v, (-0.000022278049065270225945 + 0.000029191940456521555288j), tol=ATOL) assert ae(v.real, -0.000022278049065270225945, tol=PTOL) assert ae(v.imag, 0.000029191940456521555288, tol=PTOL) v = fp.e1((20.0 - 5.0j)) assert ae(v, (4.7711374515765346894e-11 - 8.2902652405126947359e-11j), tol=ATOL) assert ae(v.real, 4.7711374515765346894e-11, tol=PTOL) assert ae(v.imag, -8.2902652405126947359e-11, tol=PTOL) v = fp.e1((80.0 - 20.0j)) assert ae(v, (3.8353473865788235787e-38 + 2.129247592349605139e-37j), tol=ATOL) assert ae(v.real, 3.8353473865788235787e-38, tol=PTOL) assert ae(v.imag, 2.129247592349605139e-37, tol=PTOL) v = fp.e1((120.0 - 30.0j)) assert ae(v, (2.3836002337480334716e-55 - 5.6704043587126198306e-55j), tol=ATOL) assert ae(v.real, 2.3836002337480334716e-55, tol=PTOL) assert ae(v.imag, -5.6704043587126198306e-55, tol=PTOL) v = fp.e1((160.0 - 40.0j)) assert ae(v, (-1.6238022898654510661e-72 + 1.104172355572287367e-72j), tol=ATOL) assert ae(v.real, -1.6238022898654510661e-72, tol=PTOL) assert ae(v.imag, 1.104172355572287367e-72, tol=PTOL) v = fp.e1((200.0 - 50.0j)) assert ae(v, (6.6800061461666228487e-90 - 1.4473816083541016115e-91j), tol=ATOL) assert ae(v.real, 6.6800061461666228487e-90, tol=PTOL) assert ae(v.imag, -1.4473816083541016115e-91, tol=PTOL) v = fp.e1((320.0 - 80.0j)) assert ae(v, (4.2737871527778786157e-143 - 3.1789935525785660314e-142j), tol=ATOL) assert ae(v.real, 4.2737871527778786157e-143, tol=PTOL) assert ae(v.imag, -3.1789935525785660314e-142, tol=PTOL) v = fp.ei(1.1641532182693481445e-10) assert ae(v, -22.296641293460247028, tol=ATOL) assert type(v) is float v = fp.ei(0.25) assert ae(v, -0.54254326466191372953, tol=ATOL) assert type(v) is float v = fp.ei(1.0) assert ae(v, 1.8951178163559367555, tol=ATOL) assert type(v) is float v = fp.ei(2.0) assert ae(v, 4.9542343560018901634, tol=ATOL) assert type(v) is float v = fp.ei(5.0) assert ae(v, 40.185275355803177455, tol=ATOL) assert type(v) is float v = fp.ei(20.0) assert ae(v, 25615652.66405658882, tol=ATOL) assert type(v) is float v = fp.ei(30.0) assert ae(v, 368973209407.27419706, tol=ATOL) assert type(v) is float v = fp.ei(40.0) assert ae(v, 6039718263611241.5784, tol=ATOL) assert type(v) is float v = fp.ei(50.0) assert ae(v, 1.0585636897131690963e+20, tol=ATOL) assert type(v) is float v = fp.ei(80.0) assert ae(v, 7.0146000049047999696e+32, tol=ATOL) assert type(v) is float v = fp.ei((1.1641532182693481445e-10 + 0.0j)) assert ae(v, (-22.296641293460247028 + 0.0j), tol=ATOL) assert ae(v.real, -22.296641293460247028, tol=PTOL) assert v.imag == 0 v = fp.ei((0.25 + 0.0j)) assert ae(v, (-0.54254326466191372953 + 0.0j), tol=ATOL) assert ae(v.real, -0.54254326466191372953, tol=PTOL) assert v.imag == 0 v = fp.ei((1.0 + 0.0j)) assert ae(v, (1.8951178163559367555 + 0.0j), tol=ATOL) assert ae(v.real, 1.8951178163559367555, tol=PTOL) assert v.imag == 0 v = fp.ei((2.0 + 0.0j)) assert ae(v, (4.9542343560018901634 + 0.0j), tol=ATOL) assert ae(v.real, 4.9542343560018901634, tol=PTOL) assert v.imag == 0 v = fp.ei((5.0 + 0.0j)) assert ae(v, (40.185275355803177455 + 0.0j), tol=ATOL) assert ae(v.real, 40.185275355803177455, tol=PTOL) assert v.imag == 0 v = fp.ei((20.0 + 0.0j)) assert ae(v, (25615652.66405658882 + 0.0j), tol=ATOL) assert ae(v.real, 25615652.66405658882, tol=PTOL) assert v.imag == 0 v = fp.ei((30.0 + 0.0j)) assert ae(v, (368973209407.27419706 + 0.0j), tol=ATOL) assert ae(v.real, 368973209407.27419706, tol=PTOL) assert v.imag == 0 v = fp.ei((40.0 + 0.0j)) assert ae(v, (6039718263611241.5784 + 0.0j), tol=ATOL) assert ae(v.real, 6039718263611241.5784, tol=PTOL) assert v.imag == 0 v = fp.ei((50.0 + 0.0j)) assert ae(v, (1.0585636897131690963e+20 + 0.0j), tol=ATOL) assert ae(v.real, 1.0585636897131690963e+20, tol=PTOL) assert v.imag == 0 v = fp.ei((80.0 + 0.0j)) assert ae(v, (7.0146000049047999696e+32 + 0.0j), tol=ATOL) assert ae(v.real, 7.0146000049047999696e+32, tol=PTOL) assert v.imag == 0 v = fp.ei((4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) assert ae(v, (-20.880034621082893023 + 0.24497866324327947603j), tol=ATOL) assert ae(v.real, -20.880034621082893023, tol=PTOL) assert ae(v.imag, 0.24497866324327947603, tol=PTOL) v = fp.ei((1.0 + 0.25j)) assert ae(v, (1.8942716983721074932 + 0.67268237088273915854j), tol=ATOL) assert ae(v.real, 1.8942716983721074932, tol=PTOL) assert ae(v.imag, 0.67268237088273915854, tol=PTOL) v = fp.ei((4.0 + 1.0j)) assert ae(v, (14.806699492675420438 + 12.280015176673582616j), tol=ATOL) assert ae(v.real, 14.806699492675420438, tol=PTOL) assert ae(v.imag, 12.280015176673582616, tol=PTOL) v = fp.ei((8.0 + 2.0j)) assert ae(v, (-54.633252667426386294 + 416.34477429173650012j), tol=ATOL) assert ae(v.real, -54.633252667426386294, tol=PTOL) assert ae(v.imag, 416.34477429173650012, tol=PTOL) v = fp.ei((20.0 + 5.0j)) assert ae(v, (711836.97165402624643 - 24745247.798103247366j), tol=ATOL) assert ae(v.real, 711836.97165402624643, tol=PTOL) assert ae(v.imag, -24745247.798103247366, tol=PTOL) v = fp.ei((80.0 + 20.0j)) assert ae(v, (4.2139911108612653091e+32 + 5.3367124741918251637e+32j), tol=ATOL) assert ae(v.real, 4.2139911108612653091e+32, tol=PTOL) assert ae(v.imag, 5.3367124741918251637e+32, tol=PTOL) v = fp.ei((120.0 + 30.0j)) assert ae(v, (-9.7760616203707508892e+48 - 1.058257682317195792e+50j), tol=ATOL) assert ae(v.real, -9.7760616203707508892e+48, tol=PTOL) assert ae(v.imag, -1.058257682317195792e+50, tol=PTOL) v = fp.ei((160.0 + 40.0j)) assert ae(v, (-8.7065541466623638861e+66 + 1.6577106725141739889e+67j), tol=ATOL) assert ae(v.real, -8.7065541466623638861e+66, tol=PTOL) assert ae(v.imag, 1.6577106725141739889e+67, tol=PTOL) v = fp.ei((200.0 + 50.0j)) assert ae(v, (3.070744996327018106e+84 - 1.7243244846769415903e+84j), tol=ATOL) assert ae(v.real, 3.070744996327018106e+84, tol=PTOL) assert ae(v.imag, -1.7243244846769415903e+84, tol=PTOL) v = fp.ei((320.0 + 80.0j)) assert ae(v, (-9.9960598637998647276e+135 - 2.6855081527595608863e+136j), tol=ATOL) assert ae(v.real, -9.9960598637998647276e+135, tol=PTOL) assert ae(v.imag, -2.6855081527595608863e+136, tol=PTOL) v = fp.ei((1.1641532182693481445e-10 + 1.1641532182693481445e-10j)) assert ae(v, (-21.950067703180274374 + 0.78539816351386363145j), tol=ATOL) assert ae(v.real, -21.950067703180274374, tol=PTOL) assert ae(v.imag, 0.78539816351386363145, tol=PTOL) v = fp.ei((0.25 + 0.25j)) assert ae(v, (-0.21441047326710323254 + 1.0683772981589995996j), tol=ATOL) assert ae(v.real, -0.21441047326710323254, tol=PTOL) assert ae(v.imag, 1.0683772981589995996, tol=PTOL) v = fp.ei((1.0 + 1.0j)) assert ae(v, (1.7646259855638540684 + 2.3877698515105224193j), tol=ATOL) assert ae(v.real, 1.7646259855638540684, tol=PTOL) assert ae(v.imag, 2.3877698515105224193, tol=PTOL) v = fp.ei((2.0 + 2.0j)) assert ae(v, (1.8920781621855474089 + 5.3169624378326579621j), tol=ATOL) assert ae(v.real, 1.8920781621855474089, tol=PTOL) assert ae(v.imag, 5.3169624378326579621, tol=PTOL) v = fp.ei((5.0 + 5.0j)) assert ae(v, (-13.470936071475245856 - 15.322492395731230968j), tol=ATOL) assert ae(v.real, -13.470936071475245856, tol=PTOL) assert ae(v.imag, -15.322492395731230968, tol=PTOL) v = fp.ei((20.0 + 20.0j)) assert ae(v, (16589317.398788971896 + 5831705.4712368307104j), tol=ATOL) assert ae(v.real, 16589317.398788971896, tol=PTOL) assert ae(v.imag, 5831705.4712368307104, tol=PTOL) v = fp.ei((30.0 + 30.0j)) assert ae(v, (-154596484273.69322527 - 204179357834.2723043j), tol=ATOL) assert ae(v.real, -154596484273.69322527, tol=PTOL) assert ae(v.imag, -204179357834.2723043, tol=PTOL) v = fp.ei((40.0 + 40.0j)) assert ae(v, (287512180321448.45408 + 4203502407932318.1156j), tol=ATOL) assert ae(v.real, 287512180321448.45408, tol=PTOL) assert ae(v.imag, 4203502407932318.1156, tol=PTOL) v = fp.ei((50.0 + 50.0j)) assert ae(v, (36128528616649268826.0 - 64648801861338741960.0j), tol=ATOL) assert ae(v.real, 36128528616649268826.0, tol=PTOL) assert ae(v.imag, -64648801861338741960.0, tol=PTOL) v = fp.ei((80.0 + 80.0j)) assert ae(v, (-3.8674816337930010217e+32 - 3.0540709639658071041e+32j), tol=ATOL) assert ae(v.real, -3.8674816337930010217e+32, tol=PTOL) assert ae(v.imag, -3.0540709639658071041e+32, tol=PTOL) v = fp.ei((1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) assert ae(v, (-20.880034621432138988 + 1.3258176641336937524j), tol=ATOL) assert ae(v.real, -20.880034621432138988, tol=PTOL) assert ae(v.imag, 1.3258176641336937524, tol=PTOL) v = fp.ei((0.25 + 1.0j)) assert ae(v, (0.59066621214766308594 + 2.3968481059377428687j), tol=ATOL) assert ae(v.real, 0.59066621214766308594, tol=PTOL) assert ae(v.imag, 2.3968481059377428687, tol=PTOL) v = fp.ei((1.0 + 4.0j)) assert ae(v, (-0.49739047283060471093 + 3.5570287076301818702j), tol=ATOL) assert ae(v.real, -0.49739047283060471093, tol=PTOL) assert ae(v.imag, 3.5570287076301818702, tol=PTOL) v = fp.ei((2.0 + 8.0j)) assert ae(v, (0.8705211147733730969 + 3.3825859385758486351j), tol=ATOL) assert ae(v.real, 0.8705211147733730969, tol=PTOL) assert ae(v.imag, 3.3825859385758486351, tol=PTOL) v = fp.ei((5.0 + 20.0j)) assert ae(v, (7.0789514293925893007 + 1.5313749363937141849j), tol=ATOL) assert ae(v.real, 7.0789514293925893007, tol=PTOL) assert ae(v.imag, 1.5313749363937141849, tol=PTOL) v = fp.ei((20.0 + 80.0j)) assert ae(v, (-5855431.4907298084434 - 720917.79156143806727j), tol=ATOL) assert ae(v.real, -5855431.4907298084434, tol=PTOL) assert ae(v.imag, -720917.79156143806727, tol=PTOL) v = fp.ei((30.0 + 120.0j)) assert ae(v, (65402491644.703470747 - 56697658396.51586764j), tol=ATOL) assert ae(v.real, 65402491644.703470747, tol=PTOL) assert ae(v.imag, -56697658396.51586764, tol=PTOL) v = fp.ei((40.0 + 160.0j)) assert ae(v, (-25504929379604.776769 + 1429035198630576.3879j), tol=ATOL) assert ae(v.real, -25504929379604.776769, tol=PTOL) assert ae(v.imag, 1429035198630576.3879, tol=PTOL) v = fp.ei((50.0 + 200.0j)) assert ae(v, (-18437746526988116954.0 - 17146362239046152342.0j), tol=ATOL) assert ae(v.real, -18437746526988116954.0, tol=PTOL) assert ae(v.imag, -17146362239046152342.0, tol=PTOL) v = fp.ei((80.0 + 320.0j)) assert ae(v, (-3.3464697299634526706e+31 - 1.6473152633843023919e+32j), tol=ATOL) assert ae(v.real, -3.3464697299634526706e+31, tol=PTOL) assert ae(v.imag, -1.6473152633843023919e+32, tol=PTOL) v = fp.ei((0.0 + 1.1641532182693481445e-10j)) assert ae(v, (-22.29664129357666235 + 1.5707963269113119411j), tol=ATOL) assert ae(v.real, -22.29664129357666235, tol=PTOL) assert ae(v.imag, 1.5707963269113119411, tol=PTOL) v = fp.ei((0.0 + 0.25j)) assert ae(v, (-0.82466306258094565309 + 1.8199298971146537833j), tol=ATOL) assert ae(v.real, -0.82466306258094565309, tol=PTOL) assert ae(v.imag, 1.8199298971146537833, tol=PTOL) v = fp.ei((0.0 + 1.0j)) assert ae(v, (0.33740392290096813466 + 2.5168793971620796342j), tol=ATOL) assert ae(v.real, 0.33740392290096813466, tol=PTOL) assert ae(v.imag, 2.5168793971620796342, tol=PTOL) v = fp.ei((0.0 + 2.0j)) assert ae(v, (0.4229808287748649957 + 3.1762093035975914678j), tol=ATOL) assert ae(v.real, 0.4229808287748649957, tol=PTOL) assert ae(v.imag, 3.1762093035975914678, tol=PTOL) v = fp.ei((0.0 + 5.0j)) assert ae(v, (-0.19002974965664387862 + 3.1207275717395707565j), tol=ATOL) assert ae(v.real, -0.19002974965664387862, tol=PTOL) assert ae(v.imag, 3.1207275717395707565, tol=PTOL) v = fp.ei((0.0 + 20.0j)) assert ae(v, (0.04441982084535331654 + 3.1190380278383364594j), tol=ATOL) assert ae(v.real, 0.04441982084535331654, tol=PTOL) assert ae(v.imag, 3.1190380278383364594, tol=PTOL) v = fp.ei((0.0 + 30.0j)) assert ae(v, (-0.033032417282071143779 + 3.1375528668252477302j), tol=ATOL) assert ae(v.real, -0.033032417282071143779, tol=PTOL) assert ae(v.imag, 3.1375528668252477302, tol=PTOL) v = fp.ei((0.0 + 40.0j)) assert ae(v, (0.019020007896208766962 + 3.157781446149681126j), tol=ATOL) assert ae(v.real, 0.019020007896208766962, tol=PTOL) assert ae(v.imag, 3.157781446149681126, tol=PTOL) v = fp.ei((0.0 + 50.0j)) assert ae(v, (-0.0056283863241163054402 + 3.122413399280832514j), tol=ATOL) assert ae(v.real, -0.0056283863241163054402, tol=PTOL) assert ae(v.imag, 3.122413399280832514, tol=PTOL) v = fp.ei((0.0 + 80.0j)) assert ae(v, (-0.012402501155070958192 + 3.1431272137073839346j), tol=ATOL) assert ae(v.real, -0.012402501155070958192, tol=PTOL) assert ae(v.imag, 3.1431272137073839346, tol=PTOL) v = fp.ei((-1.1641532182693481445e-10 + 4.6566128730773925781e-10j)) assert ae(v, (-20.880034621664969632 + 1.8157749903874220607j), tol=ATOL) assert ae(v.real, -20.880034621664969632, tol=PTOL) assert ae(v.imag, 1.8157749903874220607, tol=PTOL) v = fp.ei((-0.25 + 1.0j)) assert ae(v, (0.16868306393667788761 + 2.6557914649950505414j), tol=ATOL) assert ae(v.real, 0.16868306393667788761, tol=PTOL) assert ae(v.imag, 2.6557914649950505414, tol=PTOL) v = fp.ei((-1.0 + 4.0j)) assert ae(v, (-0.03373591813926547318 + 3.2151161058308770603j), tol=ATOL) assert ae(v.real, -0.03373591813926547318, tol=PTOL) assert ae(v.imag, 3.2151161058308770603, tol=PTOL) v = fp.ei((-2.0 + 8.0j)) assert ae(v, (0.015392833434733785143 + 3.1384179414340326969j), tol=ATOL) assert ae(v.real, 0.015392833434733785143, tol=PTOL) assert ae(v.imag, 3.1384179414340326969, tol=PTOL) v = fp.ei((-5.0 + 20.0j)) assert ae(v, (0.00024419662286542966525 + 3.1413825703601317109j), tol=ATOL) assert ae(v.real, 0.00024419662286542966525, tol=PTOL) assert ae(v.imag, 3.1413825703601317109, tol=PTOL) v = fp.ei((-20.0 + 80.0j)) assert ae(v, (-2.3255552781051330088e-11 + 3.1415926535987396304j), tol=ATOL) assert ae(v.real, -2.3255552781051330088e-11, tol=PTOL) assert ae(v.imag, 3.1415926535987396304, tol=PTOL) v = fp.ei((-30.0 + 120.0j)) assert ae(v, (2.7068919097124652332e-16 + 3.1415926535897925337j), tol=ATOL) assert ae(v.real, 2.7068919097124652332e-16, tol=PTOL) assert ae(v.imag, 3.1415926535897925337, tol=PTOL) v = fp.ei((-40.0 + 160.0j)) assert ae(v, (1.1695597827678024687e-20 + 3.1415926535897932385j), tol=ATOL) assert ae(v.real, 1.1695597827678024687e-20, tol=PTOL) assert ae(v.imag, 3.1415926535897932385, tol=PTOL) v = fp.ei((-50.0 + 200.0j)) assert ae(v, (-9.0323746914410162531e-25 + 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -9.0323746914410162531e-25, tol=PTOL) assert ae(v.imag, 3.1415926535897932385, tol=PTOL) v = fp.ei((-80.0 + 320.0j)) assert ae(v, (-3.4819106748728063576e-38 + 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -3.4819106748728063576e-38, tol=PTOL) assert ae(v.imag, 3.1415926535897932385, tol=PTOL) v = fp.ei((-4.6566128730773925781e-10 + 1.1641532182693481445e-10j)) assert ae(v, (-20.880034622014215597 + 2.8966139905793444061j), tol=ATOL) assert ae(v.real, -20.880034622014215597, tol=PTOL) assert ae(v.imag, 2.8966139905793444061, tol=PTOL) v = fp.ei((-1.0 + 0.25j)) assert ae(v, (-0.19731063945004229095 + 3.0542266078154932748j), tol=ATOL) assert ae(v.real, -0.19731063945004229095, tol=PTOL) assert ae(v.imag, 3.0542266078154932748, tol=PTOL) v = fp.ei((-4.0 + 1.0j)) assert ae(v, (-0.0013106173980145506944 + 3.1381384055698581758j), tol=ATOL) assert ae(v.real, -0.0013106173980145506944, tol=PTOL) assert ae(v.imag, 3.1381384055698581758, tol=PTOL) v = fp.ei((-8.0 + 2.0j)) assert ae(v, (0.000022278049065270225945 + 3.1415634616493367169j), tol=ATOL) assert ae(v.real, 0.000022278049065270225945, tol=PTOL) assert ae(v.imag, 3.1415634616493367169, tol=PTOL) v = fp.ei((-20.0 + 5.0j)) assert ae(v, (-4.7711374515765346894e-11 + 3.1415926536726958909j), tol=ATOL) assert ae(v.real, -4.7711374515765346894e-11, tol=PTOL) assert ae(v.imag, 3.1415926536726958909, tol=PTOL) v = fp.ei((-80.0 + 20.0j)) assert ae(v, (-3.8353473865788235787e-38 + 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -3.8353473865788235787e-38, tol=PTOL) assert ae(v.imag, 3.1415926535897932385, tol=PTOL) v = fp.ei((-120.0 + 30.0j)) assert ae(v, (-2.3836002337480334716e-55 + 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -2.3836002337480334716e-55, tol=PTOL) assert ae(v.imag, 3.1415926535897932385, tol=PTOL) v = fp.ei((-160.0 + 40.0j)) assert ae(v, (1.6238022898654510661e-72 + 3.1415926535897932385j), tol=ATOL) assert ae(v.real, 1.6238022898654510661e-72, tol=PTOL) assert ae(v.imag, 3.1415926535897932385, tol=PTOL) v = fp.ei((-200.0 + 50.0j)) assert ae(v, (-6.6800061461666228487e-90 + 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -6.6800061461666228487e-90, tol=PTOL) assert ae(v.imag, 3.1415926535897932385, tol=PTOL) v = fp.ei((-320.0 + 80.0j)) assert ae(v, (-4.2737871527778786157e-143 + 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -4.2737871527778786157e-143, tol=PTOL) assert ae(v.imag, 3.1415926535897932385, tol=PTOL) v = fp.ei(-1.1641532182693481445e-10) assert ae(v, -22.296641293693077672, tol=ATOL) assert type(v) is float v = fp.ei(-0.25) assert ae(v, -1.0442826344437381945, tol=ATOL) assert type(v) is float v = fp.ei(-1.0) assert ae(v, -0.21938393439552027368, tol=ATOL) assert type(v) is float v = fp.ei(-2.0) assert ae(v, -0.048900510708061119567, tol=ATOL) assert type(v) is float v = fp.ei(-5.0) assert ae(v, -0.0011482955912753257973, tol=ATOL) assert type(v) is float v = fp.ei(-20.0) assert ae(v, -9.8355252906498816904e-11, tol=ATOL) assert type(v) is float v = fp.ei(-30.0) assert ae(v, -3.0215520106888125448e-15, tol=ATOL) assert type(v) is float v = fp.ei(-40.0) assert ae(v, -1.0367732614516569722e-19, tol=ATOL) assert type(v) is float v = fp.ei(-50.0) assert ae(v, -3.7832640295504590187e-24, tol=ATOL) assert type(v) is float v = fp.ei(-80.0) assert ae(v, -2.2285432586884729112e-37, tol=ATOL) assert type(v) is float v = fp.ei((-1.1641532182693481445e-10 + 0.0j)) assert ae(v, (-22.296641293693077672 + 0.0j), tol=ATOL) assert ae(v.real, -22.296641293693077672, tol=PTOL) assert v.imag == 0 v = fp.ei((-0.25 + 0.0j)) assert ae(v, (-1.0442826344437381945 + 0.0j), tol=ATOL) assert ae(v.real, -1.0442826344437381945, tol=PTOL) assert v.imag == 0 v = fp.ei((-1.0 + 0.0j)) assert ae(v, (-0.21938393439552027368 + 0.0j), tol=ATOL) assert ae(v.real, -0.21938393439552027368, tol=PTOL) assert v.imag == 0 v = fp.ei((-2.0 + 0.0j)) assert ae(v, (-0.048900510708061119567 + 0.0j), tol=ATOL) assert ae(v.real, -0.048900510708061119567, tol=PTOL) assert v.imag == 0 v = fp.ei((-5.0 + 0.0j)) assert ae(v, (-0.0011482955912753257973 + 0.0j), tol=ATOL) assert ae(v.real, -0.0011482955912753257973, tol=PTOL) assert v.imag == 0 v = fp.ei((-20.0 + 0.0j)) assert ae(v, (-9.8355252906498816904e-11 + 0.0j), tol=ATOL) assert ae(v.real, -9.8355252906498816904e-11, tol=PTOL) assert v.imag == 0 v = fp.ei((-30.0 + 0.0j)) assert ae(v, (-3.0215520106888125448e-15 + 0.0j), tol=ATOL) assert ae(v.real, -3.0215520106888125448e-15, tol=PTOL) assert v.imag == 0 v = fp.ei((-40.0 + 0.0j)) assert ae(v, (-1.0367732614516569722e-19 + 0.0j), tol=ATOL) assert ae(v.real, -1.0367732614516569722e-19, tol=PTOL) assert v.imag == 0 v = fp.ei((-50.0 + 0.0j)) assert ae(v, (-3.7832640295504590187e-24 + 0.0j), tol=ATOL) assert ae(v.real, -3.7832640295504590187e-24, tol=PTOL) assert v.imag == 0 v = fp.ei((-80.0 + 0.0j)) assert ae(v, (-2.2285432586884729112e-37 + 0.0j), tol=ATOL) assert ae(v.real, -2.2285432586884729112e-37, tol=PTOL) assert v.imag == 0 v = fp.ei((-4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) assert ae(v, (-20.880034622014215597 - 2.8966139905793444061j), tol=ATOL) assert ae(v.real, -20.880034622014215597, tol=PTOL) assert ae(v.imag, -2.8966139905793444061, tol=PTOL) v = fp.ei((-1.0 - 0.25j)) assert ae(v, (-0.19731063945004229095 - 3.0542266078154932748j), tol=ATOL) assert ae(v.real, -0.19731063945004229095, tol=PTOL) assert ae(v.imag, -3.0542266078154932748, tol=PTOL) v = fp.ei((-4.0 - 1.0j)) assert ae(v, (-0.0013106173980145506944 - 3.1381384055698581758j), tol=ATOL) assert ae(v.real, -0.0013106173980145506944, tol=PTOL) assert ae(v.imag, -3.1381384055698581758, tol=PTOL) v = fp.ei((-8.0 - 2.0j)) assert ae(v, (0.000022278049065270225945 - 3.1415634616493367169j), tol=ATOL) assert ae(v.real, 0.000022278049065270225945, tol=PTOL) assert ae(v.imag, -3.1415634616493367169, tol=PTOL) v = fp.ei((-20.0 - 5.0j)) assert ae(v, (-4.7711374515765346894e-11 - 3.1415926536726958909j), tol=ATOL) assert ae(v.real, -4.7711374515765346894e-11, tol=PTOL) assert ae(v.imag, -3.1415926536726958909, tol=PTOL) v = fp.ei((-80.0 - 20.0j)) assert ae(v, (-3.8353473865788235787e-38 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -3.8353473865788235787e-38, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-120.0 - 30.0j)) assert ae(v, (-2.3836002337480334716e-55 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -2.3836002337480334716e-55, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-160.0 - 40.0j)) assert ae(v, (1.6238022898654510661e-72 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, 1.6238022898654510661e-72, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-200.0 - 50.0j)) assert ae(v, (-6.6800061461666228487e-90 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -6.6800061461666228487e-90, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-320.0 - 80.0j)) assert ae(v, (-4.2737871527778786157e-143 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -4.2737871527778786157e-143, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) assert ae(v, (-21.950067703413105017 - 2.3561944903087602507j), tol=ATOL) assert ae(v.real, -21.950067703413105017, tol=PTOL) assert ae(v.imag, -2.3561944903087602507, tol=PTOL) v = fp.ei((-0.25 - 0.25j)) assert ae(v, (-0.71092525792923287894 - 2.5766745291767512913j), tol=ATOL) assert ae(v.real, -0.71092525792923287894, tol=PTOL) assert ae(v.imag, -2.5766745291767512913, tol=PTOL) v = fp.ei((-1.0 - 1.0j)) assert ae(v, (-0.00028162445198141832551 - 2.9622681185504342983j), tol=ATOL) assert ae(v.real, -0.00028162445198141832551, tol=PTOL) assert ae(v.imag, -2.9622681185504342983, tol=PTOL) v = fp.ei((-2.0 - 2.0j)) assert ae(v, (0.033767089606562004246 - 3.1229932394200426965j), tol=ATOL) assert ae(v.real, 0.033767089606562004246, tol=PTOL) assert ae(v.imag, -3.1229932394200426965, tol=PTOL) v = fp.ei((-5.0 - 5.0j)) assert ae(v, (-0.0007266506660356393891 - 3.1420636813914284609j), tol=ATOL) assert ae(v.real, -0.0007266506660356393891, tol=PTOL) assert ae(v.imag, -3.1420636813914284609, tol=PTOL) v = fp.ei((-20.0 - 20.0j)) assert ae(v, (2.3824537449367396579e-11 - 3.1415926535228233653j), tol=ATOL) assert ae(v.real, 2.3824537449367396579e-11, tol=PTOL) assert ae(v.imag, -3.1415926535228233653, tol=PTOL) v = fp.ei((-30.0 - 30.0j)) assert ae(v, (-1.7316045841744061617e-15 - 3.141592653589794545j), tol=ATOL) assert ae(v.real, -1.7316045841744061617e-15, tol=PTOL) assert ae(v.imag, -3.141592653589794545, tol=PTOL) v = fp.ei((-40.0 - 40.0j)) assert ae(v, (7.4001043002899232182e-20 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, 7.4001043002899232182e-20, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-50.0 - 50.0j)) assert ae(v, (-2.3566128324644641219e-24 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -2.3566128324644641219e-24, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-80.0 - 80.0j)) assert ae(v, (-9.8279750572186526673e-38 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -9.8279750572186526673e-38, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) assert ae(v, (-20.880034621664969632 - 1.8157749903874220607j), tol=ATOL) assert ae(v.real, -20.880034621664969632, tol=PTOL) assert ae(v.imag, -1.8157749903874220607, tol=PTOL) v = fp.ei((-0.25 - 1.0j)) assert ae(v, (0.16868306393667788761 - 2.6557914649950505414j), tol=ATOL) assert ae(v.real, 0.16868306393667788761, tol=PTOL) assert ae(v.imag, -2.6557914649950505414, tol=PTOL) v = fp.ei((-1.0 - 4.0j)) assert ae(v, (-0.03373591813926547318 - 3.2151161058308770603j), tol=ATOL) assert ae(v.real, -0.03373591813926547318, tol=PTOL) assert ae(v.imag, -3.2151161058308770603, tol=PTOL) v = fp.ei((-2.0 - 8.0j)) assert ae(v, (0.015392833434733785143 - 3.1384179414340326969j), tol=ATOL) assert ae(v.real, 0.015392833434733785143, tol=PTOL) assert ae(v.imag, -3.1384179414340326969, tol=PTOL) v = fp.ei((-5.0 - 20.0j)) assert ae(v, (0.00024419662286542966525 - 3.1413825703601317109j), tol=ATOL) assert ae(v.real, 0.00024419662286542966525, tol=PTOL) assert ae(v.imag, -3.1413825703601317109, tol=PTOL) v = fp.ei((-20.0 - 80.0j)) assert ae(v, (-2.3255552781051330088e-11 - 3.1415926535987396304j), tol=ATOL) assert ae(v.real, -2.3255552781051330088e-11, tol=PTOL) assert ae(v.imag, -3.1415926535987396304, tol=PTOL) v = fp.ei((-30.0 - 120.0j)) assert ae(v, (2.7068919097124652332e-16 - 3.1415926535897925337j), tol=ATOL) assert ae(v.real, 2.7068919097124652332e-16, tol=PTOL) assert ae(v.imag, -3.1415926535897925337, tol=PTOL) v = fp.ei((-40.0 - 160.0j)) assert ae(v, (1.1695597827678024687e-20 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, 1.1695597827678024687e-20, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-50.0 - 200.0j)) assert ae(v, (-9.0323746914410162531e-25 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -9.0323746914410162531e-25, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((-80.0 - 320.0j)) assert ae(v, (-3.4819106748728063576e-38 - 3.1415926535897932385j), tol=ATOL) assert ae(v.real, -3.4819106748728063576e-38, tol=PTOL) assert ae(v.imag, -3.1415926535897932385, tol=PTOL) v = fp.ei((0.0 - 1.1641532182693481445e-10j)) assert ae(v, (-22.29664129357666235 - 1.5707963269113119411j), tol=ATOL) assert ae(v.real, -22.29664129357666235, tol=PTOL) assert ae(v.imag, -1.5707963269113119411, tol=PTOL) v = fp.ei((0.0 - 0.25j)) assert ae(v, (-0.82466306258094565309 - 1.8199298971146537833j), tol=ATOL) assert ae(v.real, -0.82466306258094565309, tol=PTOL) assert ae(v.imag, -1.8199298971146537833, tol=PTOL) v = fp.ei((0.0 - 1.0j)) assert ae(v, (0.33740392290096813466 - 2.5168793971620796342j), tol=ATOL) assert ae(v.real, 0.33740392290096813466, tol=PTOL) assert ae(v.imag, -2.5168793971620796342, tol=PTOL) v = fp.ei((0.0 - 2.0j)) assert ae(v, (0.4229808287748649957 - 3.1762093035975914678j), tol=ATOL) assert ae(v.real, 0.4229808287748649957, tol=PTOL) assert ae(v.imag, -3.1762093035975914678, tol=PTOL) v = fp.ei((0.0 - 5.0j)) assert ae(v, (-0.19002974965664387862 - 3.1207275717395707565j), tol=ATOL) assert ae(v.real, -0.19002974965664387862, tol=PTOL) assert ae(v.imag, -3.1207275717395707565, tol=PTOL) v = fp.ei((0.0 - 20.0j)) assert ae(v, (0.04441982084535331654 - 3.1190380278383364594j), tol=ATOL) assert ae(v.real, 0.04441982084535331654, tol=PTOL) assert ae(v.imag, -3.1190380278383364594, tol=PTOL) v = fp.ei((0.0 - 30.0j)) assert ae(v, (-0.033032417282071143779 - 3.1375528668252477302j), tol=ATOL) assert ae(v.real, -0.033032417282071143779, tol=PTOL) assert ae(v.imag, -3.1375528668252477302, tol=PTOL) v = fp.ei((0.0 - 40.0j)) assert ae(v, (0.019020007896208766962 - 3.157781446149681126j), tol=ATOL) assert ae(v.real, 0.019020007896208766962, tol=PTOL) assert ae(v.imag, -3.157781446149681126, tol=PTOL) v = fp.ei((0.0 - 50.0j)) assert ae(v, (-0.0056283863241163054402 - 3.122413399280832514j), tol=ATOL) assert ae(v.real, -0.0056283863241163054402, tol=PTOL) assert ae(v.imag, -3.122413399280832514, tol=PTOL) v = fp.ei((0.0 - 80.0j)) assert ae(v, (-0.012402501155070958192 - 3.1431272137073839346j), tol=ATOL) assert ae(v.real, -0.012402501155070958192, tol=PTOL) assert ae(v.imag, -3.1431272137073839346, tol=PTOL) v = fp.ei((1.1641532182693481445e-10 - 4.6566128730773925781e-10j)) assert ae(v, (-20.880034621432138988 - 1.3258176641336937524j), tol=ATOL) assert ae(v.real, -20.880034621432138988, tol=PTOL) assert ae(v.imag, -1.3258176641336937524, tol=PTOL) v = fp.ei((0.25 - 1.0j)) assert ae(v, (0.59066621214766308594 - 2.3968481059377428687j), tol=ATOL) assert ae(v.real, 0.59066621214766308594, tol=PTOL) assert ae(v.imag, -2.3968481059377428687, tol=PTOL) v = fp.ei((1.0 - 4.0j)) assert ae(v, (-0.49739047283060471093 - 3.5570287076301818702j), tol=ATOL) assert ae(v.real, -0.49739047283060471093, tol=PTOL) assert ae(v.imag, -3.5570287076301818702, tol=PTOL) v = fp.ei((2.0 - 8.0j)) assert ae(v, (0.8705211147733730969 - 3.3825859385758486351j), tol=ATOL) assert ae(v.real, 0.8705211147733730969, tol=PTOL) assert ae(v.imag, -3.3825859385758486351, tol=PTOL) v = fp.ei((5.0 - 20.0j)) assert ae(v, (7.0789514293925893007 - 1.5313749363937141849j), tol=ATOL) assert ae(v.real, 7.0789514293925893007, tol=PTOL) assert ae(v.imag, -1.5313749363937141849, tol=PTOL) v = fp.ei((20.0 - 80.0j)) assert ae(v, (-5855431.4907298084434 + 720917.79156143806727j), tol=ATOL) assert ae(v.real, -5855431.4907298084434, tol=PTOL) assert ae(v.imag, 720917.79156143806727, tol=PTOL) v = fp.ei((30.0 - 120.0j)) assert ae(v, (65402491644.703470747 + 56697658396.51586764j), tol=ATOL) assert ae(v.real, 65402491644.703470747, tol=PTOL) assert ae(v.imag, 56697658396.51586764, tol=PTOL) v = fp.ei((40.0 - 160.0j)) assert ae(v, (-25504929379604.776769 - 1429035198630576.3879j), tol=ATOL) assert ae(v.real, -25504929379604.776769, tol=PTOL) assert ae(v.imag, -1429035198630576.3879, tol=PTOL) v = fp.ei((50.0 - 200.0j)) assert ae(v, (-18437746526988116954.0 + 17146362239046152342.0j), tol=ATOL) assert ae(v.real, -18437746526988116954.0, tol=PTOL) assert ae(v.imag, 17146362239046152342.0, tol=PTOL) v = fp.ei((80.0 - 320.0j)) assert ae(v, (-3.3464697299634526706e+31 + 1.6473152633843023919e+32j), tol=ATOL) assert ae(v.real, -3.3464697299634526706e+31, tol=PTOL) assert ae(v.imag, 1.6473152633843023919e+32, tol=PTOL) v = fp.ei((1.1641532182693481445e-10 - 1.1641532182693481445e-10j)) assert ae(v, (-21.950067703180274374 - 0.78539816351386363145j), tol=ATOL) assert ae(v.real, -21.950067703180274374, tol=PTOL) assert ae(v.imag, -0.78539816351386363145, tol=PTOL) v = fp.ei((0.25 - 0.25j)) assert ae(v, (-0.21441047326710323254 - 1.0683772981589995996j), tol=ATOL) assert ae(v.real, -0.21441047326710323254, tol=PTOL) assert ae(v.imag, -1.0683772981589995996, tol=PTOL) v = fp.ei((1.0 - 1.0j)) assert ae(v, (1.7646259855638540684 - 2.3877698515105224193j), tol=ATOL) assert ae(v.real, 1.7646259855638540684, tol=PTOL) assert ae(v.imag, -2.3877698515105224193, tol=PTOL) v = fp.ei((2.0 - 2.0j)) assert ae(v, (1.8920781621855474089 - 5.3169624378326579621j), tol=ATOL) assert ae(v.real, 1.8920781621855474089, tol=PTOL) assert ae(v.imag, -5.3169624378326579621, tol=PTOL) v = fp.ei((5.0 - 5.0j)) assert ae(v, (-13.470936071475245856 + 15.322492395731230968j), tol=ATOL) assert ae(v.real, -13.470936071475245856, tol=PTOL) assert ae(v.imag, 15.322492395731230968, tol=PTOL) v = fp.ei((20.0 - 20.0j)) assert ae(v, (16589317.398788971896 - 5831705.4712368307104j), tol=ATOL) assert ae(v.real, 16589317.398788971896, tol=PTOL) assert ae(v.imag, -5831705.4712368307104, tol=PTOL) v = fp.ei((30.0 - 30.0j)) assert ae(v, (-154596484273.69322527 + 204179357834.2723043j), tol=ATOL) assert ae(v.real, -154596484273.69322527, tol=PTOL) assert ae(v.imag, 204179357834.2723043, tol=PTOL) v = fp.ei((40.0 - 40.0j)) assert ae(v, (287512180321448.45408 - 4203502407932318.1156j), tol=ATOL) assert ae(v.real, 287512180321448.45408, tol=PTOL) assert ae(v.imag, -4203502407932318.1156, tol=PTOL) v = fp.ei((50.0 - 50.0j)) assert ae(v, (36128528616649268826.0 + 64648801861338741960.0j), tol=ATOL) assert ae(v.real, 36128528616649268826.0, tol=PTOL) assert ae(v.imag, 64648801861338741960.0, tol=PTOL) v = fp.ei((80.0 - 80.0j)) assert ae(v, (-3.8674816337930010217e+32 + 3.0540709639658071041e+32j), tol=ATOL) assert ae(v.real, -3.8674816337930010217e+32, tol=PTOL) assert ae(v.imag, 3.0540709639658071041e+32, tol=PTOL) v = fp.ei((4.6566128730773925781e-10 - 1.1641532182693481445e-10j)) assert ae(v, (-20.880034621082893023 - 0.24497866324327947603j), tol=ATOL) assert ae(v.real, -20.880034621082893023, tol=PTOL) assert ae(v.imag, -0.24497866324327947603, tol=PTOL) v = fp.ei((1.0 - 0.25j)) assert ae(v, (1.8942716983721074932 - 0.67268237088273915854j), tol=ATOL) assert ae(v.real, 1.8942716983721074932, tol=PTOL) assert ae(v.imag, -0.67268237088273915854, tol=PTOL) v = fp.ei((4.0 - 1.0j)) assert ae(v, (14.806699492675420438 - 12.280015176673582616j), tol=ATOL) assert ae(v.real, 14.806699492675420438, tol=PTOL) assert ae(v.imag, -12.280015176673582616, tol=PTOL) v = fp.ei((8.0 - 2.0j)) assert ae(v, (-54.633252667426386294 - 416.34477429173650012j), tol=ATOL) assert ae(v.real, -54.633252667426386294, tol=PTOL) assert ae(v.imag, -416.34477429173650012, tol=PTOL) v = fp.ei((20.0 - 5.0j)) assert ae(v, (711836.97165402624643 + 24745247.798103247366j), tol=ATOL) assert ae(v.real, 711836.97165402624643, tol=PTOL) assert ae(v.imag, 24745247.798103247366, tol=PTOL) v = fp.ei((80.0 - 20.0j)) assert ae(v, (4.2139911108612653091e+32 - 5.3367124741918251637e+32j), tol=ATOL) assert ae(v.real, 4.2139911108612653091e+32, tol=PTOL) assert ae(v.imag, -5.3367124741918251637e+32, tol=PTOL) v = fp.ei((120.0 - 30.0j)) assert ae(v, (-9.7760616203707508892e+48 + 1.058257682317195792e+50j), tol=ATOL) assert ae(v.real, -9.7760616203707508892e+48, tol=PTOL) assert ae(v.imag, 1.058257682317195792e+50, tol=PTOL) v = fp.ei((160.0 - 40.0j)) assert ae(v, (-8.7065541466623638861e+66 - 1.6577106725141739889e+67j), tol=ATOL) assert ae(v.real, -8.7065541466623638861e+66, tol=PTOL) assert ae(v.imag, -1.6577106725141739889e+67, tol=PTOL) v = fp.ei((200.0 - 50.0j)) assert ae(v, (3.070744996327018106e+84 + 1.7243244846769415903e+84j), tol=ATOL) assert ae(v.real, 3.070744996327018106e+84, tol=PTOL) assert ae(v.imag, 1.7243244846769415903e+84, tol=PTOL) v = fp.ei((320.0 - 80.0j)) assert ae(v, (-9.9960598637998647276e+135 + 2.6855081527595608863e+136j), tol=ATOL) assert ae(v.real, -9.9960598637998647276e+135, tol=PTOL) assert ae(v.imag, 2.6855081527595608863e+136, tol=PTOL)
89,997
52.826555
101
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_rootfinding.py
from mpmath import * from mpmath.calculus.optimization import Secant, Muller, Bisection, Illinois, \ Pegasus, Anderson, Ridder, ANewton, Newton, MNewton, MDNewton def test_findroot(): # old tests, assuming secant mp.dps = 15 assert findroot(lambda x: 4*x-3, mpf(5)).ae(0.75) assert findroot(sin, mpf(3)).ae(pi) assert findroot(sin, (mpf(3), mpf(3.14))).ae(pi) assert findroot(lambda x: x*x+1, mpc(2+2j)).ae(1j) # test all solvers with 1 starting point f = lambda x: cos(x) for solver in [Newton, Secant, MNewton, Muller, ANewton]: x = findroot(f, 2., solver=solver) assert abs(f(x)) < eps # test all solvers with interval of 2 points for solver in [Secant, Muller, Bisection, Illinois, Pegasus, Anderson, Ridder]: x = findroot(f, (1., 2.), solver=solver) assert abs(f(x)) < eps # test types f = lambda x: (x - 2)**2 #assert isinstance(findroot(f, 1, force_type=mpf, tol=1e-10), mpf) #assert isinstance(findroot(f, 1., force_type=None, tol=1e-10), float) #assert isinstance(findroot(f, 1, force_type=complex, tol=1e-10), complex) assert isinstance(fp.findroot(f, 1, tol=1e-10), float) assert isinstance(fp.findroot(f, 1+0j, tol=1e-10), complex) def test_bisection(): # issue 273 assert findroot(lambda x: x**2-1,(0,2),solver='bisect') == 1 def test_mnewton(): f = lambda x: polyval([1,3,3,1],x) x = findroot(f, -0.9, solver='mnewton') assert abs(f(x)) < eps def test_anewton(): f = lambda x: (x - 2)**100 x = findroot(f, 1., solver=ANewton) assert abs(f(x)) < eps def test_muller(): f = lambda x: (2 + x)**3 + 2 x = findroot(f, 1., solver=Muller) assert abs(f(x)) < eps def test_multiplicity(): for i in range(1, 5): assert multiplicity(lambda x: (x - 1)**i, 1) == i assert multiplicity(lambda x: x**2, 1) == 0 def test_multidimensional(): def f(*x): return [3*x[0]**2-2*x[1]**2-1, x[0]**2-2*x[0]+x[1]**2+2*x[1]-8] assert mnorm(jacobian(f, (1,-2)) - matrix([[6,8],[0,-2]]),1) < 1.e-7 for x, error in MDNewton(mp, f, (1,-2), verbose=0, norm=lambda x: norm(x, inf)): pass assert norm(f(*x), 2) < 1e-14 # The Chinese mathematician Zhu Shijie was the very first to solve this # nonlinear system 700 years ago f1 = lambda x, y: -x + 2*y f2 = lambda x, y: (x**2 + x*(y**2 - 2) - 4*y) / (x + 4) f3 = lambda x, y: sqrt(x**2 + y**2) def f(x, y): f1x = f1(x, y) return (f2(x, y) - f1x, f3(x, y) - f1x) x = findroot(f, (10, 10)) assert [int(round(i)) for i in x] == [3, 4] def test_trivial(): assert findroot(lambda x: 0, 1) == 1 assert findroot(lambda x: x, 0) == 0 #assert findroot(lambda x, y: x + y, (1, -1)) == (1, -1)
2,831
35.307692
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_hp.py
""" Check that the output from irrational functions is accurate for high-precision input, from 5 to 200 digits. The reference values were verified with Mathematica. """ import time from mpmath import * precs = [5, 15, 28, 35, 57, 80, 100, 150, 200] # sqrt(3) + pi/2 a = \ "3.302847134363773912758768033145623809041389953497933538543279275605"\ "841220051904536395163599428307109666700184672047856353516867399774243594"\ "67433521615861420725323528325327484262075464241255915238845599752675" # e + 1/euler**2 b = \ "5.719681166601007617111261398629939965860873957353320734275716220045750"\ "31474116300529519620938123730851145473473708966080207482581266469342214"\ "824842256999042984813905047895479210702109260221361437411947323431" # sqrt(a) sqrt_a = \ "1.817373691447021556327498239690365674922395036495564333152483422755"\ "144321726165582817927383239308173567921345318453306994746434073691275094"\ "484777905906961689902608644112196725896908619756404253109722911487" # sqrt(a+b*i).real sqrt_abi_real = \ "2.225720098415113027729407777066107959851146508557282707197601407276"\ "89160998185797504198062911768240808839104987021515555650875977724230130"\ "3584116233925658621288393930286871862273400475179312570274423840384" # sqrt(a+b*i).imag sqrt_abi_imag = \ "1.2849057639084690902371581529110949983261182430040898147672052833653668"\ "0629534491275114877090834296831373498336559849050755848611854282001250"\ "1924311019152914021365263161630765255610885489295778894976075186" # log(a) log_a = \ "1.194784864491089550288313512105715261520511949410072046160598707069"\ "4336653155025770546309137440687056366757650909754708302115204338077595203"\ "83005773986664564927027147084436553262269459110211221152925732612" # log(a+b*i).real log_abi_real = \ "1.8877985921697018111624077550443297276844736840853590212962006811663"\ "04949387789489704203167470111267581371396245317618589339274243008242708"\ "014251531496104028712866224020066439049377679709216784954509456421" # log(a+b*i).imag log_abi_imag = \ "1.0471204952840802663567714297078763189256357109769672185219334169734948"\ "4265809854092437285294686651806426649541504240470168212723133326542181"\ "8300136462287639956713914482701017346851009323172531601894918640" # exp(a) exp_a = \ "27.18994224087168661137253262213293847994194869430518354305430976149"\ "382792035050358791398632888885200049857986258414049540376323785711941636"\ "100358982497583832083513086941635049329804685212200507288797531143" # exp(a+b*i).real exp_abi_real = \ "22.98606617170543596386921087657586890620262522816912505151109385026"\ "40160179326569526152851983847133513990281518417211964710397233157168852"\ "4963130831190142571659948419307628119985383887599493378056639916701" # exp(a+b*i).imag exp_abi_imag = \ "-14.523557450291489727214750571590272774669907424478129280902375851196283"\ "3377162379031724734050088565710975758824441845278120105728824497308303"\ "6065619788140201636218705414429933685889542661364184694108251449" # a**b pow_a_b = \ "928.7025342285568142947391505837660251004990092821305668257284426997"\ "361966028275685583421197860603126498884545336686124793155581311527995550"\ "580229264427202446131740932666832138634013168125809402143796691154" # (a**(a+b*i)).real pow_a_abi_real = \ "44.09156071394489511956058111704382592976814280267142206420038656267"\ "67707916510652790502399193109819563864568986234654864462095231138500505"\ "8197456514795059492120303477512711977915544927440682508821426093455" # (a**(a+b*i)).imag pow_a_abi_imag = \ "27.069371511573224750478105146737852141664955461266218367212527612279886"\ "9322304536553254659049205414427707675802193810711302947536332040474573"\ "8166261217563960235014674118610092944307893857862518964990092301" # ((a+b*i)**(a+b*i)).real pow_abi_abi_real = \ "-0.15171310677859590091001057734676423076527145052787388589334350524"\ "8084195882019497779202452975350579073716811284169068082670778986235179"\ "0813026562962084477640470612184016755250592698408112493759742219150452"\ # ((a+b*i)**(a+b*i)).imag pow_abi_abi_imag = \ "1.2697592504953448936553147870155987153192995316950583150964099070426"\ "4736837932577176947632535475040521749162383347758827307504526525647759"\ "97547638617201824468382194146854367480471892602963428122896045019902" # sin(a) sin_a = \ "-0.16055653857469062740274792907968048154164433772938156243509084009"\ "38437090841460493108570147191289893388608611542655654723437248152535114"\ "528368009465836614227575701220612124204622383149391870684288862269631" # sin(1000*a) sin_1000a = \ "-0.85897040577443833776358106803777589664322997794126153477060795801"\ "09151695416961724733492511852267067419573754315098042850381158563024337"\ "216458577140500488715469780315833217177634490142748614625281171216863" # sin(a+b*i) sin_abi_real = \ "-24.4696999681556977743346798696005278716053366404081910969773939630"\ "7149215135459794473448465734589287491880563183624997435193637389884206"\ "02151395451271809790360963144464736839412254746645151672423256977064" sin_abi_imag = \ "-150.42505378241784671801405965872972765595073690984080160750785565810981"\ "8314482499135443827055399655645954830931316357243750839088113122816583"\ "7169201254329464271121058839499197583056427233866320456505060735" # cos cos_a = \ "-0.98702664499035378399332439243967038895709261414476495730788864004"\ "05406821549361039745258003422386169330787395654908532996287293003581554"\ "257037193284199198069707141161341820684198547572456183525659969145501" cos_1000a = \ "-0.51202523570982001856195696460663971099692261342827540426136215533"\ "52686662667660613179619804463250686852463876088694806607652218586060613"\ "951310588158830695735537073667299449753951774916401887657320950496820" # tan tan_a = \ "0.162666873675188117341401059858835168007137819495998960250142156848"\ "639654718809412181543343168174807985559916643549174530459883826451064966"\ "7996119428949951351938178809444268785629011625179962457123195557310" tan_abi_real = \ "6.822696615947538488826586186310162599974827139564433912601918442911"\ "1026830824380070400102213741875804368044342309515353631134074491271890"\ "467615882710035471686578162073677173148647065131872116479947620E-6" tan_abi_imag = \ "0.9999795833048243692245661011298447587046967777739649018690797625964167"\ "1446419978852235960862841608081413169601038230073129482874832053357571"\ "62702259309150715669026865777947502665936317953101462202542168429" def test_hp(): for dps in precs: mp.dps = dps + 8 aa = mpf(a) bb = mpf(b) a1000 = 1000*mpf(a) abi = mpc(aa, bb) mp.dps = dps assert (sqrt(3) + pi/2).ae(aa) assert (e + 1/euler**2).ae(bb) assert sqrt(aa).ae(mpf(sqrt_a)) assert sqrt(abi).ae(mpc(sqrt_abi_real, sqrt_abi_imag)) assert log(aa).ae(mpf(log_a)) assert log(abi).ae(mpc(log_abi_real, log_abi_imag)) assert exp(aa).ae(mpf(exp_a)) assert exp(abi).ae(mpc(exp_abi_real, exp_abi_imag)) assert (aa**bb).ae(mpf(pow_a_b)) assert (aa**abi).ae(mpc(pow_a_abi_real, pow_a_abi_imag)) assert (abi**abi).ae(mpc(pow_abi_abi_real, pow_abi_abi_imag)) assert sin(a).ae(mpf(sin_a)) assert sin(a1000).ae(mpf(sin_1000a)) assert sin(abi).ae(mpc(sin_abi_real, sin_abi_imag)) assert cos(a).ae(mpf(cos_a)) assert cos(a1000).ae(mpf(cos_1000a)) assert tan(a).ae(mpf(tan_a)) assert tan(abi).ae(mpc(tan_abi_real, tan_abi_imag)) # check that complex cancellation is avoided so that both # real and imaginary parts have high relative accuracy. # abs_eps should be 0, but has to be set to 1e-205 to pass the # 200-digit case, probably due to slight inaccuracy in the # precomputed input assert (tan(abi).real).ae(mpf(tan_abi_real), abs_eps=1e-205) assert (tan(abi).imag).ae(mpf(tan_abi_imag), abs_eps=1e-205) mp.dps = 460 assert str(log(3))[-20:] == '02166121184001409826' mp.dps = 15 # Since str(a) can differ in the last digit from rounded a, and I want # to compare the last digits of big numbers with the results in Mathematica, # I made this hack to get the last 20 digits of rounded a def last_digits(a): r = repr(a) s = str(a) #dps = mp.dps #mp.dps += 3 m = 10 r = r.replace(s[:-m],'') r = r.replace("mpf('",'').replace("')",'') num0 = 0 for c in r: if c == '0': num0 += 1 else: break b = float(int(r))/10**(len(r) - m) if b >= 10**m - 0.5: raise NotImplementedError n = int(round(b)) sn = str(n) s = s[:-m] + '0'*num0 + sn return s[-20:] # values checked with Mathematica def test_log_hp(): mp.dps = 2000 a = mpf(10)**15000/3 r = log(a) res = last_digits(r) # Mathematica N[Log[10^15000/3], 2000] # ...7443804441768333470331 assert res == '44380444176833347033' # see issue 145 r = log(mpf(3)/2) # Mathematica N[Log[3/2], 2000] # ...69653749808140753263288 res = last_digits(r) assert res == '53749808140753263288' mp.dps = 10000 r = log(2) res = last_digits(r) # Mathematica N[Log[2], 10000] # ...695615913401856601359655561 assert res == '91340185660135965556' r = log(mpf(10)**10/3) res = last_digits(r) # Mathematica N[Log[10^10/3], 10000] # ...587087654020631943060007154 assert res == '54020631943060007154', res r = log(mpf(10)**100/3) res = last_digits(r) # Mathematica N[Log[10^100/3], 10000] # ,,,59246336539088351652334666 assert res == '36539088351652334666', res mp.dps += 10 a = 1 - mpf(1)/10**10 mp.dps -= 10 r = log(a) res = last_digits(r) # ...3310334360482956137216724048322957404 # 372167240483229574038733026370 # Mathematica N[Log[1 - 10^-10]*10^10, 10000] # ...60482956137216724048322957404 assert res == '37216724048322957404', res mp.dps = 10000 mp.dps += 100 a = 1 + mpf(1)/10**100 mp.dps -= 100 r = log(a) res = last_digits(+r) # Mathematica N[Log[1 + 10^-100]*10^10, 10030] # ...3994733877377412241546890854692521568292338268273 10^-91 assert res == '39947338773774122415', res mp.dps = 15 def test_exp_hp(): mp.dps = 4000 r = exp(mpf(1)/10) # IntegerPart[N[Exp[1/10] * 10^4000, 4000]] # ...92167105162069688129 assert int(r * 10**mp.dps) % 10**20 == 92167105162069688129
10,441
34.760274
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/runtests.py
#!/usr/bin/env python """ python runtests.py -py Use py.test to run tests (more useful for debugging) python runtests.py -psyco Enable psyco to make tests run about 50% faster python runtests.py -coverage Generate test coverage report. Statistics are written to /tmp python runtests.py -profile Generate profile stats (this is much slower) python runtests.py -nogmpy Run tests without using GMPY even if it exists python runtests.py -strict Enforce extra tests in normalize() python runtests.py -local Insert '../..' at the beginning of sys.path to use local mpmath Additional arguments are used to filter the tests to run. Only files that have one of the arguments in their name are executed. """ import sys, os, traceback if "-psyco" in sys.argv: sys.argv.remove('-psyco') import psyco psyco.full() profile = False if "-profile" in sys.argv: sys.argv.remove('-profile') profile = True coverage = False if "-coverage" in sys.argv: sys.argv.remove('-coverage') coverage = True if "-nogmpy" in sys.argv: sys.argv.remove('-nogmpy') os.environ['MPMATH_NOGMPY'] = 'Y' if "-strict" in sys.argv: sys.argv.remove('-strict') os.environ['MPMATH_STRICT'] = 'Y' if "-local" in sys.argv: sys.argv.remove('-local') importdir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..')) else: importdir = '' # TODO: add a flag for this testdir = '' def testit(importdir='', testdir=''): """Run all tests in testdir while importing from importdir.""" if importdir: sys.path.insert(1, importdir) if testdir: sys.path.insert(1, testdir) import os.path import mpmath print("mpmath imported from %s" % os.path.dirname(mpmath.__file__)) print("mpmath backend: %s" % mpmath.libmp.backend.BACKEND) print("mpmath mp class: %s" % repr(mpmath.mp)) print("mpmath version: %s" % mpmath.__version__) print("Python version: %s" % sys.version) print("") if "-py" in sys.argv: sys.argv.remove('-py') import py py.test.cmdline.main() else: import glob from timeit import default_timer as clock modules = [] args = sys.argv[1:] # search for tests in directory of this file if not otherwise specified if not testdir: pattern = os.path.dirname(sys.argv[0]) else: pattern = testdir if pattern: pattern += '/' pattern += 'test*.py' # look for tests (respecting specified filter) for f in glob.glob(pattern): name = os.path.splitext(os.path.basename(f))[0] # If run as a script, only run tests given as args, if any are given if args and __name__ == "__main__": ok = False for arg in args: if arg in name: ok = True break if not ok: continue module = __import__(name) priority = module.__dict__.get('priority', 100) if priority == 666: modules = [[priority, name, module]] break modules.append([priority, name, module]) # execute tests modules.sort() tstart = clock() for priority, name, module in modules: print(name) for f in sorted(module.__dict__.keys()): if f.startswith('test_'): if coverage and ('numpy' in f): continue sys.stdout.write(" " + f[5:].ljust(25) + " ") t1 = clock() try: module.__dict__[f]() except: etype, evalue, trb = sys.exc_info() if etype in (KeyboardInterrupt, SystemExit): raise print("") print("TEST FAILED!") print("") traceback.print_exc() t2 = clock() print("ok " + " " + ("%.7f" % (t2-t1)) + " s") tend = clock() print("") print("finished tests in " + ("%.2f" % (tend-tstart)) + " seconds") # clean sys.path if importdir: sys.path.remove(importdir) if testdir: sys.path.remove(testdir) if __name__ == '__main__': if profile: import cProfile cProfile.run("testit('%s', '%s')" % (importdir, testdir), sort=1) elif coverage: import trace tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], trace=0, count=1) tracer.run('testit(importdir, testdir)') r = tracer.results() r.write_results(show_missing=True, summary=True, coverdir="/tmp") else: testit(importdir, testdir)
4,985
30.358491
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_elliptic.py
""" Limited tests of the elliptic functions module. A full suite of extensive testing can be found in elliptic_torture_tests.py Author of the first version: M.T. Taschuk References: [1] Abramowitz & Stegun. 'Handbook of Mathematical Functions, 9th Ed.', (Dover duplicate of 1972 edition) [2] Whittaker 'A Course of Modern Analysis, 4th Ed.', 1946, Cambridge University Press """ import mpmath import random from mpmath import * def mpc_ae(a, b, eps=eps): res = True res = res and a.real.ae(b.real, eps) res = res and a.imag.ae(b.imag, eps) return res zero = mpf(0) one = mpf(1) jsn = ellipfun('sn') jcn = ellipfun('cn') jdn = ellipfun('dn') calculate_nome = lambda k: qfrom(k=k) def test_ellipfun(): mp.dps = 15 assert ellipfun('ss', 0, 0) == 1 assert ellipfun('cc', 0, 0) == 1 assert ellipfun('dd', 0, 0) == 1 assert ellipfun('nn', 0, 0) == 1 assert ellipfun('sn', 0.25, 0).ae(sin(0.25)) assert ellipfun('cn', 0.25, 0).ae(cos(0.25)) assert ellipfun('dn', 0.25, 0).ae(1) assert ellipfun('ns', 0.25, 0).ae(csc(0.25)) assert ellipfun('nc', 0.25, 0).ae(sec(0.25)) assert ellipfun('nd', 0.25, 0).ae(1) assert ellipfun('sc', 0.25, 0).ae(tan(0.25)) assert ellipfun('sd', 0.25, 0).ae(sin(0.25)) assert ellipfun('cd', 0.25, 0).ae(cos(0.25)) assert ellipfun('cs', 0.25, 0).ae(cot(0.25)) assert ellipfun('dc', 0.25, 0).ae(sec(0.25)) assert ellipfun('ds', 0.25, 0).ae(csc(0.25)) assert ellipfun('sn', 0.25, 1).ae(tanh(0.25)) assert ellipfun('cn', 0.25, 1).ae(sech(0.25)) assert ellipfun('dn', 0.25, 1).ae(sech(0.25)) assert ellipfun('ns', 0.25, 1).ae(coth(0.25)) assert ellipfun('nc', 0.25, 1).ae(cosh(0.25)) assert ellipfun('nd', 0.25, 1).ae(cosh(0.25)) assert ellipfun('sc', 0.25, 1).ae(sinh(0.25)) assert ellipfun('sd', 0.25, 1).ae(sinh(0.25)) assert ellipfun('cd', 0.25, 1).ae(1) assert ellipfun('cs', 0.25, 1).ae(csch(0.25)) assert ellipfun('dc', 0.25, 1).ae(1) assert ellipfun('ds', 0.25, 1).ae(csch(0.25)) assert ellipfun('sn', 0.25, 0.5).ae(0.24615967096986145833) assert ellipfun('cn', 0.25, 0.5).ae(0.96922928989378439337) assert ellipfun('dn', 0.25, 0.5).ae(0.98473484156599474563) assert ellipfun('ns', 0.25, 0.5).ae(4.0624038700573130369) assert ellipfun('nc', 0.25, 0.5).ae(1.0317476065024692949) assert ellipfun('nd', 0.25, 0.5).ae(1.0155017958029488665) assert ellipfun('sc', 0.25, 0.5).ae(0.25397465134058993408) assert ellipfun('sd', 0.25, 0.5).ae(0.24997558792415733063) assert ellipfun('cd', 0.25, 0.5).ae(0.98425408443195497052) assert ellipfun('cs', 0.25, 0.5).ae(3.9374008182374110826) assert ellipfun('dc', 0.25, 0.5).ae(1.0159978158253033913) assert ellipfun('ds', 0.25, 0.5).ae(4.0003906313579720593) def test_calculate_nome(): mp.dps = 100 q = calculate_nome(zero) assert(q == zero) mp.dps = 25 # used Mathematica's EllipticNomeQ[m] math1 = [(mpf(1)/10, mpf('0.006584651553858370274473060')), (mpf(2)/10, mpf('0.01394285727531826872146409')), (mpf(3)/10, mpf('0.02227743615715350822901627')), (mpf(4)/10, mpf('0.03188334731336317755064299')), (mpf(5)/10, mpf('0.04321391826377224977441774')), (mpf(6)/10, mpf('0.05702025781460967637754953')), (mpf(7)/10, mpf('0.07468994353717944761143751')), (mpf(8)/10, mpf('0.09927369733882489703607378')), (mpf(9)/10, mpf('0.1401731269542615524091055')), (mpf(9)/10, mpf('0.1401731269542615524091055'))] for i in math1: m = i[0] q = calculate_nome(sqrt(m)) assert q.ae(i[1]) mp.dps = 15 def test_jtheta(): mp.dps = 25 z = q = zero for n in range(1,5): value = jtheta(n, z, q) assert(value == (n-1)//2) for q in [one, mpf(2)]: for n in range(1,5): raised = True try: r = jtheta(n, z, q) except: pass else: raised = False assert(raised) z = one/10 q = one/11 # Mathematical N[EllipticTheta[1, 1/10, 1/11], 25] res = mpf('0.1069552990104042681962096') result = jtheta(1, z, q) assert(result.ae(res)) # Mathematica N[EllipticTheta[2, 1/10, 1/11], 25] res = mpf('1.101385760258855791140606') result = jtheta(2, z, q) assert(result.ae(res)) # Mathematica N[EllipticTheta[3, 1/10, 1/11], 25] res = mpf('1.178319743354331061795905') result = jtheta(3, z, q) assert(result.ae(res)) # Mathematica N[EllipticTheta[4, 1/10, 1/11], 25] res = mpf('0.8219318954665153577314573') result = jtheta(4, z, q) assert(result.ae(res)) # test for sin zeros for jtheta(1, z, q) # test for cos zeros for jtheta(2, z, q) z1 = pi z2 = pi/2 for i in range(10): qstring = str(random.random()) q = mpf(qstring) result = jtheta(1, z1, q) assert(result.ae(0)) result = jtheta(2, z2, q) assert(result.ae(0)) mp.dps = 15 def test_jtheta_issue_79(): # near the circle of covergence |q| = 1 the convergence slows # down; for |q| > Q_LIM the theta functions raise ValueError mp.dps = 30 mp.dps += 30 q = mpf(6)/10 - one/10**6 - mpf(8)/10 * j mp.dps -= 30 # Mathematica run first # N[EllipticTheta[3, 1, 6/10 - 10^-6 - 8/10*I], 2000] # then it works: # N[EllipticTheta[3, 1, 6/10 - 10^-6 - 8/10*I], 30] res = mpf('32.0031009628901652627099524264') + \ mpf('16.6153027998236087899308935624') * j result = jtheta(3, 1, q) # check that for abs(q) > Q_LIM a ValueError exception is raised mp.dps += 30 q = mpf(6)/10 - one/10**7 - mpf(8)/10 * j mp.dps -= 30 try: result = jtheta(3, 1, q) except ValueError: pass else: assert(False) # bug reported in issue 79 mp.dps = 100 z = (1+j)/3 q = mpf(368983957219251)/10**15 + mpf(636363636363636)/10**15 * j # Mathematica N[EllipticTheta[1, z, q], 35] res = mpf('2.4439389177990737589761828991467471') + \ mpf('0.5446453005688226915290954851851490') *j mp.dps = 30 result = jtheta(1, z, q) assert(result.ae(res)) mp.dps = 80 z = 3 + 4*j q = 0.5 + 0.5*j r1 = jtheta(1, z, q) mp.dps = 15 r2 = jtheta(1, z, q) assert r1.ae(r2) mp.dps = 80 z = 3 + j q1 = exp(j*3) # longer test # for n in range(1, 6) for n in range(1, 2): mp.dps = 80 q = q1*(1 - mpf(1)/10**n) r1 = jtheta(1, z, q) mp.dps = 15 r2 = jtheta(1, z, q) assert r1.ae(r2) mp.dps = 15 # issue 79 about high derivatives assert jtheta(3, 4.5, 0.25, 9).ae(1359.04892680683) assert jtheta(3, 4.5, 0.25, 50).ae(-6.14832772630905e+33) mp.dps = 50 r = jtheta(3, 4.5, 0.25, 9) assert r.ae('1359.048926806828939547859396600218966947753213803') r = jtheta(3, 4.5, 0.25, 50) assert r.ae('-6148327726309051673317975084654262.4119215720343656') def test_jtheta_identities(): """ Tests the some of the jacobi identidies found in Abramowitz, Sec. 16.28, Pg. 576. The identities are tested to 1 part in 10^98. """ mp.dps = 110 eps1 = ldexp(eps, 30) for i in range(10): qstring = str(random.random()) q = mpf(qstring) zstring = str(10*random.random()) z = mpf(zstring) # Abramowitz 16.28.1 # v_1(z, q)**2 * v_4(0, q)**2 = v_3(z, q)**2 * v_2(0, q)**2 # - v_2(z, q)**2 * v_3(0, q)**2 term1 = (jtheta(1, z, q)**2) * (jtheta(4, zero, q)**2) term2 = (jtheta(3, z, q)**2) * (jtheta(2, zero, q)**2) term3 = (jtheta(2, z, q)**2) * (jtheta(3, zero, q)**2) equality = term1 - term2 + term3 assert(equality.ae(0, eps1)) zstring = str(100*random.random()) z = mpf(zstring) # Abramowitz 16.28.2 # v_2(z, q)**2 * v_4(0, q)**2 = v_4(z, q)**2 * v_2(0, q)**2 # - v_1(z, q)**2 * v_3(0, q)**2 term1 = (jtheta(2, z, q)**2) * (jtheta(4, zero, q)**2) term2 = (jtheta(4, z, q)**2) * (jtheta(2, zero, q)**2) term3 = (jtheta(1, z, q)**2) * (jtheta(3, zero, q)**2) equality = term1 - term2 + term3 assert(equality.ae(0, eps1)) # Abramowitz 16.28.3 # v_3(z, q)**2 * v_4(0, q)**2 = v_4(z, q)**2 * v_3(0, q)**2 # - v_1(z, q)**2 * v_2(0, q)**2 term1 = (jtheta(3, z, q)**2) * (jtheta(4, zero, q)**2) term2 = (jtheta(4, z, q)**2) * (jtheta(3, zero, q)**2) term3 = (jtheta(1, z, q)**2) * (jtheta(2, zero, q)**2) equality = term1 - term2 + term3 assert(equality.ae(0, eps1)) # Abramowitz 16.28.4 # v_4(z, q)**2 * v_4(0, q)**2 = v_3(z, q)**2 * v_3(0, q)**2 # - v_2(z, q)**2 * v_2(0, q)**2 term1 = (jtheta(4, z, q)**2) * (jtheta(4, zero, q)**2) term2 = (jtheta(3, z, q)**2) * (jtheta(3, zero, q)**2) term3 = (jtheta(2, z, q)**2) * (jtheta(2, zero, q)**2) equality = term1 - term2 + term3 assert(equality.ae(0, eps1)) # Abramowitz 16.28.5 # v_2(0, q)**4 + v_4(0, q)**4 == v_3(0, q)**4 term1 = (jtheta(2, zero, q))**4 term2 = (jtheta(4, zero, q))**4 term3 = (jtheta(3, zero, q))**4 equality = term1 + term2 - term3 assert(equality.ae(0, eps1)) mp.dps = 15 def test_jtheta_complex(): mp.dps = 30 z = mpf(1)/4 + j/8 q = mpf(1)/3 + j/7 # Mathematica N[EllipticTheta[1, 1/4 + I/8, 1/3 + I/7], 35] res = mpf('0.31618034835986160705729105731678285') + \ mpf('0.07542013825835103435142515194358975') * j r = jtheta(1, z, q) assert(mpc_ae(r, res)) # Mathematica N[EllipticTheta[2, 1/4 + I/8, 1/3 + I/7], 35] res = mpf('1.6530986428239765928634711417951828') + \ mpf('0.2015344864707197230526742145361455') * j r = jtheta(2, z, q) assert(mpc_ae(r, res)) # Mathematica N[EllipticTheta[3, 1/4 + I/8, 1/3 + I/7], 35] res = mpf('1.6520564411784228184326012700348340') + \ mpf('0.1998129119671271328684690067401823') * j r = jtheta(3, z, q) assert(mpc_ae(r, res)) # Mathematica N[EllipticTheta[4, 1/4 + I/8, 1/3 + I/7], 35] res = mpf('0.37619082382228348252047624089973824') - \ mpf('0.15623022130983652972686227200681074') * j r = jtheta(4, z, q) assert(mpc_ae(r, res)) # check some theta function identities mp.dos = 100 z = mpf(1)/4 + j/8 q = mpf(1)/3 + j/7 mp.dps += 10 a = [0,0, jtheta(2, 0, q), jtheta(3, 0, q), jtheta(4, 0, q)] t = [0, jtheta(1, z, q), jtheta(2, z, q), jtheta(3, z, q), jtheta(4, z, q)] r = [(t[2]*a[4])**2 - (t[4]*a[2])**2 + (t[1] *a[3])**2, (t[3]*a[4])**2 - (t[4]*a[3])**2 + (t[1] *a[2])**2, (t[1]*a[4])**2 - (t[3]*a[2])**2 + (t[2] *a[3])**2, (t[4]*a[4])**2 - (t[3]*a[3])**2 + (t[2] *a[2])**2, a[2]**4 + a[4]**4 - a[3]**4] mp.dps -= 10 for x in r: assert(mpc_ae(x, mpc(0))) mp.dps = 15 def test_djtheta(): mp.dps = 30 z = one/7 + j/3 q = one/8 + j/5 # Mathematica N[EllipticThetaPrime[1, 1/7 + I/3, 1/8 + I/5], 35] res = mpf('1.5555195883277196036090928995803201') - \ mpf('0.02439761276895463494054149673076275') * j result = jtheta(1, z, q, 1) assert(mpc_ae(result, res)) # Mathematica N[EllipticThetaPrime[2, 1/7 + I/3, 1/8 + I/5], 35] res = mpf('0.19825296689470982332701283509685662') - \ mpf('0.46038135182282106983251742935250009') * j result = jtheta(2, z, q, 1) assert(mpc_ae(result, res)) # Mathematica N[EllipticThetaPrime[3, 1/7 + I/3, 1/8 + I/5], 35] res = mpf('0.36492498415476212680896699407390026') - \ mpf('0.57743812698666990209897034525640369') * j result = jtheta(3, z, q, 1) assert(mpc_ae(result, res)) # Mathematica N[EllipticThetaPrime[4, 1/7 + I/3, 1/8 + I/5], 35] res = mpf('-0.38936892528126996010818803742007352') + \ mpf('0.66549886179739128256269617407313625') * j result = jtheta(4, z, q, 1) assert(mpc_ae(result, res)) for i in range(10): q = (one*random.random() + j*random.random())/2 # identity in Wittaker, Watson &21.41 a = jtheta(1, 0, q, 1) b = jtheta(2, 0, q)*jtheta(3, 0, q)*jtheta(4, 0, q) assert(a.ae(b)) # test higher derivatives mp.dps = 20 for q,z in [(one/3, one/5), (one/3 + j/8, one/5), (one/3, one/5 + j/8), (one/3 + j/7, one/5 + j/8)]: for n in [1, 2, 3, 4]: r = jtheta(n, z, q, 2) r1 = diff(lambda zz: jtheta(n, zz, q), z, n=2) assert r.ae(r1) r = jtheta(n, z, q, 3) r1 = diff(lambda zz: jtheta(n, zz, q), z, n=3) assert r.ae(r1) # identity in Wittaker, Watson &21.41 q = one/3 z = zero a = [0]*5 a[1] = jtheta(1, z, q, 3)/jtheta(1, z, q, 1) for n in [2,3,4]: a[n] = jtheta(n, z, q, 2)/jtheta(n, z, q) equality = a[2] + a[3] + a[4] - a[1] assert(equality.ae(0)) mp.dps = 15 def test_jsn(): """ Test some special cases of the sn(z, q) function. """ mp.dps = 100 # trival case result = jsn(zero, zero) assert(result == zero) # Abramowitz Table 16.5 # # sn(0, m) = 0 for i in range(10): qstring = str(random.random()) q = mpf(qstring) equality = jsn(zero, q) assert(equality.ae(0)) # Abramowitz Table 16.6.1 # # sn(z, 0) = sin(z), m == 0 # # sn(z, 1) = tanh(z), m == 1 # # It would be nice to test these, but I find that they run # in to numerical trouble. I'm currently treating as a boundary # case for sn function. mp.dps = 25 arg = one/10 #N[JacobiSN[1/10, 2^-100], 25] res = mpf('0.09983341664682815230681420') m = ldexp(one, -100) result = jsn(arg, m) assert(result.ae(res)) # N[JacobiSN[1/10, 1/10], 25] res = mpf('0.09981686718599080096451168') result = jsn(arg, arg) assert(result.ae(res)) mp.dps = 15 def test_jcn(): """ Test some special cases of the cn(z, q) function. """ mp.dps = 100 # Abramowitz Table 16.5 # cn(0, q) = 1 qstring = str(random.random()) q = mpf(qstring) cn = jcn(zero, q) assert(cn.ae(one)) # Abramowitz Table 16.6.2 # # cn(u, 0) = cos(u), m == 0 # # cn(u, 1) = sech(z), m == 1 # # It would be nice to test these, but I find that they run # in to numerical trouble. I'm currently treating as a boundary # case for cn function. mp.dps = 25 arg = one/10 m = ldexp(one, -100) #N[JacobiCN[1/10, 2^-100], 25] res = mpf('0.9950041652780257660955620') result = jcn(arg, m) assert(result.ae(res)) # N[JacobiCN[1/10, 1/10], 25] res = mpf('0.9950058256237368748520459') result = jcn(arg, arg) assert(result.ae(res)) mp.dps = 15 def test_jdn(): """ Test some special cases of the dn(z, q) function. """ mp.dps = 100 # Abramowitz Table 16.5 # dn(0, q) = 1 mstring = str(random.random()) m = mpf(mstring) dn = jdn(zero, m) assert(dn.ae(one)) mp.dps = 25 # N[JacobiDN[1/10, 1/10], 25] res = mpf('0.9995017055025556219713297') arg = one/10 result = jdn(arg, arg) assert(result.ae(res)) mp.dps = 15 def test_sn_cn_dn_identities(): """ Tests the some of the jacobi elliptic function identities found on Mathworld. Haven't found in Abramowitz. """ mp.dps = 100 N = 5 for i in range(N): qstring = str(random.random()) q = mpf(qstring) zstring = str(100*random.random()) z = mpf(zstring) # MathWorld # sn(z, q)**2 + cn(z, q)**2 == 1 term1 = jsn(z, q)**2 term2 = jcn(z, q)**2 equality = one - term1 - term2 assert(equality.ae(0)) # MathWorld # k**2 * sn(z, m)**2 + dn(z, m)**2 == 1 for i in range(N): mstring = str(random.random()) m = mpf(qstring) k = m.sqrt() zstring = str(10*random.random()) z = mpf(zstring) term1 = k**2 * jsn(z, m)**2 term2 = jdn(z, m)**2 equality = one - term1 - term2 assert(equality.ae(0)) for i in range(N): mstring = str(random.random()) m = mpf(mstring) k = m.sqrt() zstring = str(random.random()) z = mpf(zstring) # MathWorld # k**2 * cn(z, m)**2 + (1 - k**2) = dn(z, m)**2 term1 = k**2 * jcn(z, m)**2 term2 = 1 - k**2 term3 = jdn(z, m)**2 equality = term3 - term1 - term2 assert(equality.ae(0)) K = ellipk(k**2) # Abramowitz Table 16.5 # sn(K, m) = 1; K is K(k), first complete elliptic integral r = jsn(K, m) assert(r.ae(one)) # Abramowitz Table 16.5 # cn(K, q) = 0; K is K(k), first complete elliptic integral equality = jcn(K, m) assert(equality.ae(0)) # Abramowitz Table 16.6.3 # dn(z, 0) = 1, m == 0 z = m value = jdn(z, zero) assert(value.ae(one)) mp.dps = 15 def test_sn_cn_dn_complex(): mp.dps = 30 # N[JacobiSN[1/4 + I/8, 1/3 + I/7], 35] in Mathematica res = mpf('0.2495674401066275492326652143537') + \ mpf('0.12017344422863833381301051702823') * j u = mpf(1)/4 + j/8 m = mpf(1)/3 + j/7 r = jsn(u, m) assert(mpc_ae(r, res)) #N[JacobiCN[1/4 + I/8, 1/3 + I/7], 35] res = mpf('0.9762691700944007312693721148331') - \ mpf('0.0307203994181623243583169154824')*j r = jcn(u, m) #assert r.real.ae(res.real) #assert r.imag.ae(res.imag) assert(mpc_ae(r, res)) #N[JacobiDN[1/4 + I/8, 1/3 + I/7], 35] res = mpf('0.99639490163039577560547478589753039') - \ mpf('0.01346296520008176393432491077244994')*j r = jdn(u, m) assert(mpc_ae(r, res)) mp.dps = 15 def test_elliptic_integrals(): # Test cases from Carlson's paper mp.dps = 15 assert elliprd(0,2,1).ae(1.7972103521033883112) assert elliprd(2,3,4).ae(0.16510527294261053349) assert elliprd(j,-j,2).ae(0.65933854154219768919) assert elliprd(0,j,-j).ae(1.2708196271909686299 + 2.7811120159520578777j) assert elliprd(0,j-1,j).ae(-1.8577235439239060056 - 0.96193450888838559989j) assert elliprd(-2-j,-j,-1+j).ae(1.8249027393703805305 - 1.2218475784827035855j) # extra test cases assert elliprg(0,0,0) == 0 assert elliprg(0,0,16).ae(2) assert elliprg(0,16,0).ae(2) assert elliprg(16,0,0).ae(2) assert elliprg(1,4,0).ae(1.2110560275684595248036) assert elliprg(1,0,4).ae(1.2110560275684595248036) assert elliprg(0,4,1).ae(1.2110560275684595248036) # should be symmetric -- fixes a bug present in the paper x,y,z = 1,1j,-1+1j assert elliprg(x,y,z).ae(0.64139146875812627545 + 0.58085463774808290907j) assert elliprg(x,z,y).ae(0.64139146875812627545 + 0.58085463774808290907j) assert elliprg(y,x,z).ae(0.64139146875812627545 + 0.58085463774808290907j) assert elliprg(y,z,x).ae(0.64139146875812627545 + 0.58085463774808290907j) assert elliprg(z,x,y).ae(0.64139146875812627545 + 0.58085463774808290907j) assert elliprg(z,y,x).ae(0.64139146875812627545 + 0.58085463774808290907j) for n in [5, 15, 30, 60, 100]: mp.dps = n assert elliprf(1,2,0).ae('1.3110287771460599052324197949455597068413774757158115814084108519003952935352071251151477664807145467230678763') assert elliprf(0.5,1,0).ae('1.854074677301371918433850347195260046217598823521766905585928045056021776838119978357271861650371897277771871') assert elliprf(j,-j,0).ae('1.854074677301371918433850347195260046217598823521766905585928045056021776838119978357271861650371897277771871') assert elliprf(j-1,j,0).ae(mpc('0.79612586584233913293056938229563057846592264089185680214929401744498956943287031832657642790719940442165621412', '-1.2138566698364959864300942567386038975419875860741507618279563735753073152507112254567291141460317931258599889')) assert elliprf(2,3,4).ae('0.58408284167715170669284916892566789240351359699303216166309375305508295130412919665541330837704050454472379308') assert elliprf(j,-j,2).ae('1.0441445654064360931078658361850779139591660747973017593275012615517220315993723776182276555339288363064476126') assert elliprf(j-1,j,1-j).ae(mpc('0.93912050218619371196624617169781141161485651998254431830645241993282941057500174238125105410055253623847335313', '-0.53296252018635269264859303449447908970360344322834582313172115220559316331271520508208025270300138589669326136')) assert elliprc(0,0.25).ae(+pi) assert elliprc(2.25,2).ae(+ln2) assert elliprc(0,j).ae(mpc('1.1107207345395915617539702475151734246536554223439225557713489017391086982748684776438317336911913093408525532', '-1.1107207345395915617539702475151734246536554223439225557713489017391086982748684776438317336911913093408525532')) assert elliprc(-j,j).ae(mpc('1.2260849569072198222319655083097718755633725139745941606203839524036426936825652935738621522906572884239069297', '-0.34471136988767679699935618332997956653521218571295874986708834375026550946053920574015526038040124556716711353')) assert elliprc(0.25,-2).ae(ln2/3) assert elliprc(j,-1).ae(mpc('0.77778596920447389875196055840799837589537035343923012237628610795937014001905822029050288316217145443865649819', '0.1983248499342877364755170948292130095921681309577950696116251029742793455964385947473103628983664877025779304')) assert elliprj(0,1,2,3).ae('0.77688623778582332014190282640545501102298064276022952731669118325952563819813258230708177398475643634103990878') assert elliprj(2,3,4,5).ae('0.14297579667156753833233879421985774801466647854232626336218889885463800128817976132826443904216546421431528308') assert elliprj(2,3,4,-1+j).ae(mpc('0.13613945827770535203521374457913768360237593025944342652613569368333226052158214183059386307242563164036672709', '-0.38207561624427164249600936454845112611060375760094156571007648297226090050927156176977091273224510621553615189')) assert elliprj(j,-j,0,2).ae('1.6490011662710884518243257224860232300246792717163891216346170272567376981346412066066050103935109581019055806') assert elliprj(-1+j,-1-j,1,2).ae('0.94148358841220238083044612133767270187474673547917988681610772381758628963408843935027667916713866133196845063') assert elliprj(j,-j,0,1-j).ae(mpc('1.8260115229009316249372594065790946657011067182850435297162034335356430755397401849070610280860044610878657501', '1.2290661908643471500163617732957042849283739403009556715926326841959667290840290081010472716420690899886276961')) assert elliprj(-1+j,-1-j,1,-3+j).ae(mpc('-0.61127970812028172123588152373622636829986597243716610650831553882054127570542477508023027578037045504958619422', '-1.0684038390006807880182112972232562745485871763154040245065581157751693730095703406209466903752930797510491155')) assert elliprj(-1+j,-2-j,-j,-1+j).ae(mpc('1.8249027393703805304622013339009022294368078659619988943515764258335975852685224202567854526307030593012768954', '-1.2218475784827035854568450371590419833166777535029296025352291308244564398645467465067845461070602841312456831')) assert elliprg(0,16,16).ae(+pi) assert elliprg(2,3,4).ae('1.7255030280692277601061148835701141842692457170470456590515892070736643637303053506944907685301315299153040991') assert elliprg(0,j,-j).ae('0.42360654239698954330324956174109581824072295516347109253028968632986700241706737986160014699730561497106114281') assert elliprg(j-1,j,0).ae(mpc('0.44660591677018372656731970402124510811555212083508861036067729944477855594654762496407405328607219895053798354', '0.70768352357515390073102719507612395221369717586839400605901402910893345301718731499237159587077682267374159282')) assert elliprg(-j,j-1,j).ae(mpc('0.36023392184473309033675652092928695596803358846377334894215349632203382573844427952830064383286995172598964266', '0.40348623401722113740956336997761033878615232917480045914551915169013722542827052849476969199578321834819903921')) assert elliprg(0, mpf('0.0796'), 4).ae('1.0284758090288040009838871385180217366569777284430590125081211090574701293154645750017813190805144572673802094') mp.dps = 15 def test_issue_238(): assert isnan(qfrom(m=nan))
24,819
36.492447
164
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_quad.py
from mpmath import * def ae(a, b): return abs(a-b) < 10**(-mp.dps+5) def test_basic_integrals(): for prec in [15, 30, 100]: mp.dps = prec assert ae(quadts(lambda x: x**3 - 3*x**2, [-2, 4]), -12) assert ae(quadgl(lambda x: x**3 - 3*x**2, [-2, 4]), -12) assert ae(quadts(sin, [0, pi]), 2) assert ae(quadts(sin, [0, 2*pi]), 0) assert ae(quadts(exp, [-inf, -1]), 1/e) assert ae(quadts(lambda x: exp(-x), [0, inf]), 1) assert ae(quadts(lambda x: exp(-x*x), [-inf, inf]), sqrt(pi)) assert ae(quadts(lambda x: 1/(1+x*x), [-1, 1]), pi/2) assert ae(quadts(lambda x: 1/(1+x*x), [-inf, inf]), pi) assert ae(quadts(lambda x: 2*sqrt(1-x*x), [-1, 1]), pi) mp.dps = 15 def test_quad_symmetry(): assert quadts(sin, [-1, 1]) == 0 assert quadgl(sin, [-1, 1]) == 0 def test_quad_infinite_mirror(): # Check mirrored infinite interval assert ae(quad(lambda x: exp(-x*x), [inf,-inf]), -sqrt(pi)) assert ae(quad(lambda x: exp(x), [0,-inf]), -1) def test_quadgl_linear(): assert quadgl(lambda x: x, [0, 1], maxdegree=1).ae(0.5) def test_complex_integration(): assert quadts(lambda x: x, [0, 1+j]).ae(j) def test_quadosc(): mp.dps = 15 assert quadosc(lambda x: sin(x)/x, [0, inf], period=2*pi).ae(pi/2) # Double integrals def test_double_trivial(): assert ae(quadts(lambda x, y: x, [0, 1], [0, 1]), 0.5) assert ae(quadts(lambda x, y: x, [-1, 1], [-1, 1]), 0.0) def test_double_1(): assert ae(quadts(lambda x, y: cos(x+y/2), [-pi/2, pi/2], [0, pi]), 4) def test_double_2(): assert ae(quadts(lambda x, y: (x-1)/((1-x*y)*log(x*y)), [0, 1], [0, 1]), euler) def test_double_3(): assert ae(quadts(lambda x, y: 1/sqrt(1+x*x+y*y), [-1, 1], [-1, 1]), 4*log(2+sqrt(3))-2*pi/3) def test_double_4(): assert ae(quadts(lambda x, y: 1/(1-x*x * y*y), [0, 1], [0, 1]), pi**2 / 8) def test_double_5(): assert ae(quadts(lambda x, y: 1/(1-x*y), [0, 1], [0, 1]), pi**2 / 6) def test_double_6(): assert ae(quadts(lambda x, y: exp(-(x+y)), [0, inf], [0, inf]), 1) # fails def xtest_double_7(): assert ae(quadts(lambda x, y: exp(-x*x-y*y), [-inf, inf], [-inf, inf]), pi) # Test integrals from "Experimentation in Mathematics" by Borwein, # Bailey & Girgensohn def test_expmath_integrals(): for prec in [15, 30, 50]: mp.dps = prec assert ae(quadts(lambda x: x/sinh(x), [0, inf]), pi**2 / 4) assert ae(quadts(lambda x: log(x)**2 / (1+x**2), [0, inf]), pi**3 / 8) assert ae(quadts(lambda x: (1+x**2)/(1+x**4), [0, inf]), pi/sqrt(2)) assert ae(quadts(lambda x: log(x)/cosh(x)**2, [0, inf]), log(pi)-2*log(2)-euler) assert ae(quadts(lambda x: log(1+x**3)/(1-x+x**2), [0, inf]), 2*pi*log(3)/sqrt(3)) assert ae(quadts(lambda x: log(x)**2 / (x**2+x+1), [0, 1]), 8*pi**3 / (81*sqrt(3))) assert ae(quadts(lambda x: log(cos(x))**2, [0, pi/2]), pi/2 * (log(2)**2+pi**2/12)) assert ae(quadts(lambda x: x**2 / sin(x)**2, [0, pi/2]), pi*log(2)) assert ae(quadts(lambda x: x**2/sqrt(exp(x)-1), [0, inf]), 4*pi*(log(2)**2 + pi**2/12)) assert ae(quadts(lambda x: x*exp(-x)*sqrt(1-exp(-2*x)), [0, inf]), pi*(1+2*log(2))/8) mp.dps = 15 # Do not reach full accuracy def xtest_expmath_fail(): assert ae(quadts(lambda x: sqrt(tan(x)), [0, pi/2]), pi*sqrt(2)/2) assert ae(quadts(lambda x: atan(x)/(x*sqrt(1-x**2)), [0, 1]), pi*log(1+sqrt(2))/2) assert ae(quadts(lambda x: log(1+x**2)/x**2, [0, 1]), pi/2-log(2)) assert ae(quadts(lambda x: x**2/((1+x**4)*sqrt(1-x**4)), [0, 1]), pi/8)
3,731
40.010989
104
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_basic_ops.py
import mpmath from mpmath import * from mpmath.libmp import * import random import sys try: long = long except NameError: long = int def test_type_compare(): assert mpf(2) == mpc(2,0) assert mpf(0) == mpc(0) assert mpf(2) != mpc(2, 0.00001) assert mpf(2) == 2.0 assert mpf(2) != 3.0 assert mpf(2) == 2 assert mpf(2) != '2.0' assert mpc(2) != '2.0' def test_add(): assert mpf(2.5) + mpf(3) == 5.5 assert mpf(2.5) + 3 == 5.5 assert mpf(2.5) + 3.0 == 5.5 assert 3 + mpf(2.5) == 5.5 assert 3.0 + mpf(2.5) == 5.5 assert (3+0j) + mpf(2.5) == 5.5 assert mpc(2.5) + mpf(3) == 5.5 assert mpc(2.5) + 3 == 5.5 assert mpc(2.5) + 3.0 == 5.5 assert mpc(2.5) + (3+0j) == 5.5 assert 3 + mpc(2.5) == 5.5 assert 3.0 + mpc(2.5) == 5.5 assert (3+0j) + mpc(2.5) == 5.5 def test_sub(): assert mpf(2.5) - mpf(3) == -0.5 assert mpf(2.5) - 3 == -0.5 assert mpf(2.5) - 3.0 == -0.5 assert 3 - mpf(2.5) == 0.5 assert 3.0 - mpf(2.5) == 0.5 assert (3+0j) - mpf(2.5) == 0.5 assert mpc(2.5) - mpf(3) == -0.5 assert mpc(2.5) - 3 == -0.5 assert mpc(2.5) - 3.0 == -0.5 assert mpc(2.5) - (3+0j) == -0.5 assert 3 - mpc(2.5) == 0.5 assert 3.0 - mpc(2.5) == 0.5 assert (3+0j) - mpc(2.5) == 0.5 def test_mul(): assert mpf(2.5) * mpf(3) == 7.5 assert mpf(2.5) * 3 == 7.5 assert mpf(2.5) * 3.0 == 7.5 assert 3 * mpf(2.5) == 7.5 assert 3.0 * mpf(2.5) == 7.5 assert (3+0j) * mpf(2.5) == 7.5 assert mpc(2.5) * mpf(3) == 7.5 assert mpc(2.5) * 3 == 7.5 assert mpc(2.5) * 3.0 == 7.5 assert mpc(2.5) * (3+0j) == 7.5 assert 3 * mpc(2.5) == 7.5 assert 3.0 * mpc(2.5) == 7.5 assert (3+0j) * mpc(2.5) == 7.5 def test_div(): assert mpf(6) / mpf(3) == 2.0 assert mpf(6) / 3 == 2.0 assert mpf(6) / 3.0 == 2.0 assert 6 / mpf(3) == 2.0 assert 6.0 / mpf(3) == 2.0 assert (6+0j) / mpf(3.0) == 2.0 assert mpc(6) / mpf(3) == 2.0 assert mpc(6) / 3 == 2.0 assert mpc(6) / 3.0 == 2.0 assert mpc(6) / (3+0j) == 2.0 assert 6 / mpc(3) == 2.0 assert 6.0 / mpc(3) == 2.0 assert (6+0j) / mpc(3) == 2.0 def test_pow(): assert mpf(6) ** mpf(3) == 216.0 assert mpf(6) ** 3 == 216.0 assert mpf(6) ** 3.0 == 216.0 assert 6 ** mpf(3) == 216.0 assert 6.0 ** mpf(3) == 216.0 assert (6+0j) ** mpf(3.0) == 216.0 assert mpc(6) ** mpf(3) == 216.0 assert mpc(6) ** 3 == 216.0 assert mpc(6) ** 3.0 == 216.0 assert mpc(6) ** (3+0j) == 216.0 assert 6 ** mpc(3) == 216.0 assert 6.0 ** mpc(3) == 216.0 assert (6+0j) ** mpc(3) == 216.0 def test_mixed_misc(): assert 1 + mpf(3) == mpf(3) + 1 == 4 assert 1 - mpf(3) == -(mpf(3) - 1) == -2 assert 3 * mpf(2) == mpf(2) * 3 == 6 assert 6 / mpf(2) == mpf(6) / 2 == 3 assert 1.0 + mpf(3) == mpf(3) + 1.0 == 4 assert 1.0 - mpf(3) == -(mpf(3) - 1.0) == -2 assert 3.0 * mpf(2) == mpf(2) * 3.0 == 6 assert 6.0 / mpf(2) == mpf(6) / 2.0 == 3 def test_add_misc(): mp.dps = 15 assert mpf(4) + mpf(-70) == -66 assert mpf(1) + mpf(1.1)/80 == 1 + 1.1/80 assert mpf((1, 10000000000)) + mpf(3) == mpf((1, 10000000000)) assert mpf(3) + mpf((1, 10000000000)) == mpf((1, 10000000000)) assert mpf((1, -10000000000)) + mpf(3) == mpf(3) assert mpf(3) + mpf((1, -10000000000)) == mpf(3) assert mpf(1) + 1e-15 != 1 assert mpf(1) + 1e-20 == 1 assert mpf(1.07e-22) + 0 == mpf(1.07e-22) assert mpf(0) + mpf(1.07e-22) == mpf(1.07e-22) def test_complex_misc(): # many more tests needed assert 1 + mpc(2) == 3 assert not mpc(2).ae(2 + 1e-13) assert mpc(2+1e-15j).ae(2) def test_complex_zeros(): for a in [0,2]: for b in [0,3]: for c in [0,4]: for d in [0,5]: assert mpc(a,b)*mpc(c,d) == complex(a,b)*complex(c,d) def test_hash(): for i in range(-256, 256): assert hash(mpf(i)) == hash(i) assert hash(mpf(0.5)) == hash(0.5) assert hash(mpc(2,3)) == hash(2+3j) # Check that this doesn't fail assert hash(inf) # Check that overflow doesn't assign equal hashes to large numbers assert hash(mpf('1e1000')) != hash('1e10000') assert hash(mpc(100,'1e1000')) != hash(mpc(200,'1e1000')) from mpmath.rational import mpq assert hash(mp.mpq(1,3)) assert hash(mp.mpq(0,1)) == 0 assert hash(mp.mpq(-1,1)) == hash(-1) assert hash(mp.mpq(1,1)) == hash(1) assert hash(mp.mpq(5,1)) == hash(5) assert hash(mp.mpq(1,2)) == hash(0.5) if sys.version >= "3.2": assert hash(mpf(1)*2**2000) == hash(2**2000) assert hash(mpf(1)/2**2000) == hash(mpq(1,2**2000)) # Advanced rounding test def test_add_rounding(): mp.dps = 15 a = from_float(1e-50) assert mpf_sub(mpf_add(fone, a, 53, round_up), fone, 53, round_up) == from_float(2.2204460492503131e-16) assert mpf_sub(fone, a, 53, round_up) == fone assert mpf_sub(fone, mpf_sub(fone, a, 53, round_down), 53, round_down) == from_float(1.1102230246251565e-16) assert mpf_add(fone, a, 53, round_down) == fone def test_almost_equal(): assert mpf(1.2).ae(mpf(1.20000001), 1e-7) assert not mpf(1.2).ae(mpf(1.20000001), 1e-9) assert not mpf(-0.7818314824680298).ae(mpf(-0.774695868667929)) def test_arithmetic_functions(): import operator ops = [(operator.add, fadd), (operator.sub, fsub), (operator.mul, fmul), (operator.truediv, fdiv)] a = mpf(0.27) b = mpf(1.13) c = mpc(0.51+2.16j) d = mpc(1.08-0.99j) for x in [a,b,c,d]: for y in [a,b,c,d]: for op, fop in ops: if fop is not fdiv: mp.prec = 200 z0 = op(x,y) mp.prec = 60 z1 = op(x,y) mp.prec = 53 z2 = op(x,y) assert fop(x, y, prec=60) == z1 assert fop(x, y) == z2 if fop is not fdiv: assert fop(x, y, prec=inf) == z0 assert fop(x, y, dps=inf) == z0 assert fop(x, y, exact=True) == z0 assert fneg(fneg(z1, exact=True), prec=inf) == z1 assert fneg(z1) == -(+z1) mp.dps = 15 def test_exact_integer_arithmetic(): # XXX: re-fix this so that all operations are tested with all rounding modes random.seed(0) for prec in [6, 10, 25, 40, 100, 250, 725]: for rounding in ['d', 'u', 'f', 'c', 'n']: mp.dps = prec M = 10**(prec-2) M2 = 10**(prec//2-2) for i in range(10): a = random.randint(-M, M) b = random.randint(-M, M) assert mpf(a, rounding=rounding) == a assert int(mpf(a, rounding=rounding)) == a assert int(mpf(str(a), rounding=rounding)) == a assert mpf(a) + mpf(b) == a + b assert mpf(a) - mpf(b) == a - b assert -mpf(a) == -a a = random.randint(-M2, M2) b = random.randint(-M2, M2) assert mpf(a) * mpf(b) == a*b assert mpf_mul(from_int(a), from_int(b), mp.prec, rounding) == from_int(a*b) mp.dps = 15 def test_odd_int_bug(): assert to_int(from_int(3), round_nearest) == 3 def test_str_1000_digits(): mp.dps = 1001 # last digit may be wrong assert str(mpf(2)**0.5)[-10:-1] == '9518488472'[:9] assert str(pi)[-10:-1] == '2164201989'[:9] mp.dps = 15 def test_str_10000_digits(): mp.dps = 10001 # last digit may be wrong assert str(mpf(2)**0.5)[-10:-1] == '5873258351'[:9] assert str(pi)[-10:-1] == '5256375678'[:9] mp.dps = 15 def test_monitor(): f = lambda x: x**2 a = [] b = [] g = monitor(f, a.append, b.append) assert g(3) == 9 assert g(4) == 16 assert a[0] == ((3,), {}) assert b[0] == 9 def test_nint_distance(): assert nint_distance(mpf(-3)) == (-3, -inf) assert nint_distance(mpc(-3)) == (-3, -inf) assert nint_distance(mpf(-3.1)) == (-3, -3) assert nint_distance(mpf(-3.01)) == (-3, -6) assert nint_distance(mpf(-3.001)) == (-3, -9) assert nint_distance(mpf(-3.0001)) == (-3, -13) assert nint_distance(mpf(-2.9)) == (-3, -3) assert nint_distance(mpf(-2.99)) == (-3, -6) assert nint_distance(mpf(-2.999)) == (-3, -9) assert nint_distance(mpf(-2.9999)) == (-3, -13) assert nint_distance(mpc(-3+0.1j)) == (-3, -3) assert nint_distance(mpc(-3+0.01j)) == (-3, -6) assert nint_distance(mpc(-3.1+0.1j)) == (-3, -3) assert nint_distance(mpc(-3.01+0.01j)) == (-3, -6) assert nint_distance(mpc(-3.001+0.001j)) == (-3, -9) assert nint_distance(mpf(0)) == (0, -inf) assert nint_distance(mpf(0.01)) == (0, -6) assert nint_distance(mpf('1e-100')) == (0, -332) def test_floor_ceil_nint_frac(): mp.dps = 15 for n in range(-10,10): assert floor(n) == n assert floor(n+0.5) == n assert ceil(n) == n assert ceil(n+0.5) == n+1 assert nint(n) == n # nint rounds to even if n % 2 == 1: assert nint(n+0.5) == n+1 else: assert nint(n+0.5) == n assert floor(inf) == inf assert floor(ninf) == ninf assert isnan(floor(nan)) assert ceil(inf) == inf assert ceil(ninf) == ninf assert isnan(ceil(nan)) assert nint(inf) == inf assert nint(ninf) == ninf assert isnan(nint(nan)) assert floor(0.1) == 0 assert floor(0.9) == 0 assert floor(-0.1) == -1 assert floor(-0.9) == -1 assert floor(10000000000.1) == 10000000000 assert floor(10000000000.9) == 10000000000 assert floor(-10000000000.1) == -10000000000-1 assert floor(-10000000000.9) == -10000000000-1 assert floor(1e-100) == 0 assert floor(-1e-100) == -1 assert floor(1e100) == 1e100 assert floor(-1e100) == -1e100 assert ceil(0.1) == 1 assert ceil(0.9) == 1 assert ceil(-0.1) == 0 assert ceil(-0.9) == 0 assert ceil(10000000000.1) == 10000000000+1 assert ceil(10000000000.9) == 10000000000+1 assert ceil(-10000000000.1) == -10000000000 assert ceil(-10000000000.9) == -10000000000 assert ceil(1e-100) == 1 assert ceil(-1e-100) == 0 assert ceil(1e100) == 1e100 assert ceil(-1e100) == -1e100 assert nint(0.1) == 0 assert nint(0.9) == 1 assert nint(-0.1) == 0 assert nint(-0.9) == -1 assert nint(10000000000.1) == 10000000000 assert nint(10000000000.9) == 10000000000+1 assert nint(-10000000000.1) == -10000000000 assert nint(-10000000000.9) == -10000000000-1 assert nint(1e-100) == 0 assert nint(-1e-100) == 0 assert nint(1e100) == 1e100 assert nint(-1e100) == -1e100 assert floor(3.2+4.6j) == 3+4j assert ceil(3.2+4.6j) == 4+5j assert nint(3.2+4.6j) == 3+5j for n in range(-10,10): assert frac(n) == 0 assert frac(0.25) == 0.25 assert frac(1.25) == 0.25 assert frac(2.25) == 0.25 assert frac(-0.25) == 0.75 assert frac(-1.25) == 0.75 assert frac(-2.25) == 0.75 assert frac('1e100000000000000') == 0 u = mpf('1e-100000000000000') assert frac(u) == u assert frac(-u) == 1 # rounding! u = mpf('1e-400') assert frac(-u, prec=0) == fsub(1, u, exact=True) assert frac(3.25+4.75j) == 0.25+0.75j def test_isnan_etc(): from mpmath.rational import mpq assert isnan(nan) == True assert isnan(3) == False assert isnan(mpf(3)) == False assert isnan(inf) == False assert isnan(mpc(2,nan)) == True assert isnan(mpc(2,nan)) == True assert isnan(mpc(nan,nan)) == True assert isnan(mpc(2,2)) == False assert isnan(mpc(nan,inf)) == True assert isnan(mpc(inf,inf)) == False assert isnan(mpq((3,2))) == False assert isnan(mpq((0,1))) == False assert isinf(inf) == True assert isinf(-inf) == True assert isinf(3) == False assert isinf(nan) == False assert isinf(3+4j) == False assert isinf(mpc(inf)) == True assert isinf(mpc(3,inf)) == True assert isinf(mpc(inf,3)) == True assert isinf(mpc(inf,inf)) == True assert isinf(mpc(nan,inf)) == True assert isinf(mpc(inf,nan)) == True assert isinf(mpc(nan,nan)) == False assert isinf(mpq((3,2))) == False assert isinf(mpq((0,1))) == False assert isnormal(3) == True assert isnormal(3.5) == True assert isnormal(mpf(3.5)) == True assert isnormal(0) == False assert isnormal(mpf(0)) == False assert isnormal(0.0) == False assert isnormal(inf) == False assert isnormal(-inf) == False assert isnormal(nan) == False assert isnormal(float(inf)) == False assert isnormal(mpc(0,0)) == False assert isnormal(mpc(3,0)) == True assert isnormal(mpc(0,3)) == True assert isnormal(mpc(3,3)) == True assert isnormal(mpc(0,nan)) == False assert isnormal(mpc(0,inf)) == False assert isnormal(mpc(3,nan)) == False assert isnormal(mpc(3,inf)) == False assert isnormal(mpc(3,-inf)) == False assert isnormal(mpc(nan,0)) == False assert isnormal(mpc(inf,0)) == False assert isnormal(mpc(nan,3)) == False assert isnormal(mpc(inf,3)) == False assert isnormal(mpc(inf,nan)) == False assert isnormal(mpc(nan,inf)) == False assert isnormal(mpc(nan,nan)) == False assert isnormal(mpc(inf,inf)) == False assert isnormal(mpq((3,2))) == True assert isnormal(mpq((0,1))) == False assert isint(3) == True assert isint(0) == True assert isint(long(3)) == True assert isint(long(0)) == True assert isint(mpf(3)) == True assert isint(mpf(0)) == True assert isint(mpf(-3)) == True assert isint(mpf(3.2)) == False assert isint(3.2) == False assert isint(nan) == False assert isint(inf) == False assert isint(-inf) == False assert isint(mpc(0)) == True assert isint(mpc(3)) == True assert isint(mpc(3.2)) == False assert isint(mpc(3,inf)) == False assert isint(mpc(inf)) == False assert isint(mpc(3,2)) == False assert isint(mpc(0,2)) == False assert isint(mpc(3,2),gaussian=True) == True assert isint(mpc(3,0),gaussian=True) == True assert isint(mpc(0,3),gaussian=True) == True assert isint(3+4j) == False assert isint(3+4j, gaussian=True) == True assert isint(3+0j) == True assert isint(mpq((3,2))) == False assert isint(mpq((3,9))) == False assert isint(mpq((9,3))) == True assert isint(mpq((0,4))) == True assert isint(mpq((1,1))) == True assert isint(mpq((-1,1))) == True assert mp.isnpint(0) == True assert mp.isnpint(1) == False assert mp.isnpint(-1) == True assert mp.isnpint(-1.1) == False assert mp.isnpint(-1.0) == True assert mp.isnpint(mp.mpq(1,2)) == False assert mp.isnpint(mp.mpq(-1,2)) == False assert mp.isnpint(mp.mpq(-3,1)) == True assert mp.isnpint(mp.mpq(0,1)) == True assert mp.isnpint(mp.mpq(1,1)) == False assert mp.isnpint(0+0j) == True assert mp.isnpint(-1+0j) == True assert mp.isnpint(-1.1+0j) == False assert mp.isnpint(-1+0.1j) == False assert mp.isnpint(0+0.1j) == False
15,199
33.080717
112
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/tests/test_identify.py
from mpmath import * def test_pslq(): mp.dps = 15 assert pslq([3*pi+4*e/7, pi, e, log(2)]) == [7, -21, -4, 0] assert pslq([4.9999999999999991, 1]) == [1, -5] assert pslq([2,1]) == [1, -2] def test_identify(): mp.dps = 20 assert identify(zeta(4), ['log(2)', 'pi**4']) == '((1/90)*pi**4)' mp.dps = 15 assert identify(exp(5)) == 'exp(5)' assert identify(exp(4)) == 'exp(4)' assert identify(log(5)) == 'log(5)' assert identify(exp(3*pi), ['pi']) == 'exp((3*pi))' assert identify(3, full=True) == ['3', '3', '1/(1/3)', 'sqrt(9)', '1/sqrt((1/9))', '(sqrt(12)/2)**2', '1/(sqrt(12)/6)**2'] assert identify(pi+1, {'a':+pi}) == '(1 + 1*a)'
692
33.65
69
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/libmpf.py
""" Low-level functions for arbitrary-precision floating-point arithmetic. """ __docformat__ = 'plaintext' import math from bisect import bisect import sys # Importing random is slow #from random import getrandbits getrandbits = None from .backend import (MPZ, MPZ_TYPE, MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_FIVE, BACKEND, STRICT, HASH_MODULUS, HASH_BITS, gmpy, sage, sage_utils) from .libintmath import (giant_steps, trailtable, bctable, lshift, rshift, bitcount, trailing, sqrt_fixed, numeral, isqrt, isqrt_fast, sqrtrem, bin_to_radix) # We don't pickle tuples directly for the following reasons: # 1: pickle uses str() for ints, which is inefficient when they are large # 2: pickle doesn't work for gmpy mpzs # Both problems are solved by using hex() if BACKEND == 'sage': def to_pickable(x): sign, man, exp, bc = x return sign, hex(man), exp, bc else: def to_pickable(x): sign, man, exp, bc = x return sign, hex(man)[2:], exp, bc def from_pickable(x): sign, man, exp, bc = x return (sign, MPZ(man, 16), exp, bc) class ComplexResult(ValueError): pass try: intern except NameError: intern = lambda x: x # All supported rounding modes round_nearest = intern('n') round_floor = intern('f') round_ceiling = intern('c') round_up = intern('u') round_down = intern('d') round_fast = round_down def prec_to_dps(n): """Return number of accurate decimals that can be represented with a precision of n bits.""" return max(1, int(round(int(n)/3.3219280948873626)-1)) def dps_to_prec(n): """Return the number of bits required to represent n decimals accurately.""" return max(1, int(round((int(n)+1)*3.3219280948873626))) def repr_dps(n): """Return the number of decimal digits required to represent a number with n-bit precision so that it can be uniquely reconstructed from the representation.""" dps = prec_to_dps(n) if dps == 15: return 17 return dps + 3 #----------------------------------------------------------------------------# # Some commonly needed float values # #----------------------------------------------------------------------------# # Regular number format: # (-1)**sign * mantissa * 2**exponent, plus bitcount of mantissa fzero = (0, MPZ_ZERO, 0, 0) fnzero = (1, MPZ_ZERO, 0, 0) fone = (0, MPZ_ONE, 0, 1) fnone = (1, MPZ_ONE, 0, 1) ftwo = (0, MPZ_ONE, 1, 1) ften = (0, MPZ_FIVE, 1, 3) fhalf = (0, MPZ_ONE, -1, 1) # Arbitrary encoding for special numbers: zero mantissa, nonzero exponent fnan = (0, MPZ_ZERO, -123, -1) finf = (0, MPZ_ZERO, -456, -2) fninf = (1, MPZ_ZERO, -789, -3) # Was 1e1000; this is broken in Python 2.4 math_float_inf = 1e300 * 1e300 #----------------------------------------------------------------------------# # Rounding # #----------------------------------------------------------------------------# # This function can be used to round a mantissa generally. However, # we will try to do most rounding inline for efficiency. def round_int(x, n, rnd): if rnd == round_nearest: if x >= 0: t = x >> (n-1) if t & 1 and ((t & 2) or (x & h_mask[n<300][n])): return (t>>1)+1 else: return t>>1 else: return -round_int(-x, n, rnd) if rnd == round_floor: return x >> n if rnd == round_ceiling: return -((-x) >> n) if rnd == round_down: if x >= 0: return x >> n return -((-x) >> n) if rnd == round_up: if x >= 0: return -((-x) >> n) return x >> n # These masks are used to pick out segments of numbers to determine # which direction to round when rounding to nearest. class h_mask_big: def __getitem__(self, n): return (MPZ_ONE<<(n-1))-1 h_mask_small = [0]+[((MPZ_ONE<<(_-1))-1) for _ in range(1, 300)] h_mask = [h_mask_big(), h_mask_small] # The >> operator rounds to floor. shifts_down[rnd][sign] # tells whether this is the right direction to use, or if the # number should be negated before shifting shifts_down = {round_floor:(1,0), round_ceiling:(0,1), round_down:(1,1), round_up:(0,0)} #----------------------------------------------------------------------------# # Normalization of raw mpfs # #----------------------------------------------------------------------------# # This function is called almost every time an mpf is created. # It has been optimized accordingly. def _normalize(sign, man, exp, bc, prec, rnd): """ Create a raw mpf tuple with value (-1)**sign * man * 2**exp and normalized mantissa. The mantissa is rounded in the specified direction if its size exceeds the precision. Trailing zero bits are also stripped from the mantissa to ensure that the representation is canonical. Conditions on the input: * The input must represent a regular (finite) number * The sign bit must be 0 or 1 * The mantissa must be positive * The exponent must be an integer * The bitcount must be exact If these conditions are not met, use from_man_exp, mpf_pos, or any of the conversion functions to create normalized raw mpf tuples. """ if not man: return fzero # Cut mantissa down to size if larger than target precision n = bc - prec if n > 0: if rnd == round_nearest: t = man >> (n-1) if t & 1 and ((t & 2) or (man & h_mask[n<300][n])): man = (t>>1)+1 else: man = t>>1 elif shifts_down[rnd][sign]: man >>= n else: man = -((-man)>>n) exp += n bc = prec # Strip trailing bits if not man & 1: t = trailtable[int(man & 255)] if not t: while not man & 255: man >>= 8 exp += 8 bc -= 8 t = trailtable[int(man & 255)] man >>= t exp += t bc -= t # Bit count can be wrong if the input mantissa was 1 less than # a power of 2 and got rounded up, thereby adding an extra bit. # With trailing bits removed, all powers of two have mantissa 1, # so this is easy to check for. if man == 1: bc = 1 return sign, man, exp, bc def _normalize1(sign, man, exp, bc, prec, rnd): """same as normalize, but with the added condition that man is odd or zero """ if not man: return fzero if bc <= prec: return sign, man, exp, bc n = bc - prec if rnd == round_nearest: t = man >> (n-1) if t & 1 and ((t & 2) or (man & h_mask[n<300][n])): man = (t>>1)+1 else: man = t>>1 elif shifts_down[rnd][sign]: man >>= n else: man = -((-man)>>n) exp += n bc = prec # Strip trailing bits if not man & 1: t = trailtable[int(man & 255)] if not t: while not man & 255: man >>= 8 exp += 8 bc -= 8 t = trailtable[int(man & 255)] man >>= t exp += t bc -= t # Bit count can be wrong if the input mantissa was 1 less than # a power of 2 and got rounded up, thereby adding an extra bit. # With trailing bits removed, all powers of two have mantissa 1, # so this is easy to check for. if man == 1: bc = 1 return sign, man, exp, bc try: _exp_types = (int, long) except NameError: _exp_types = (int,) def strict_normalize(sign, man, exp, bc, prec, rnd): """Additional checks on the components of an mpf. Enable tests by setting the environment variable MPMATH_STRICT to Y.""" assert type(man) == MPZ_TYPE assert type(bc) in _exp_types assert type(exp) in _exp_types assert bc == bitcount(man) return _normalize(sign, man, exp, bc, prec, rnd) def strict_normalize1(sign, man, exp, bc, prec, rnd): """Additional checks on the components of an mpf. Enable tests by setting the environment variable MPMATH_STRICT to Y.""" assert type(man) == MPZ_TYPE assert type(bc) in _exp_types assert type(exp) in _exp_types assert bc == bitcount(man) assert (not man) or (man & 1) return _normalize1(sign, man, exp, bc, prec, rnd) if BACKEND == 'gmpy' and '_mpmath_normalize' in dir(gmpy): _normalize = gmpy._mpmath_normalize _normalize1 = gmpy._mpmath_normalize if BACKEND == 'sage': _normalize = _normalize1 = sage_utils.normalize if STRICT: normalize = strict_normalize normalize1 = strict_normalize1 else: normalize = _normalize normalize1 = _normalize1 #----------------------------------------------------------------------------# # Conversion functions # #----------------------------------------------------------------------------# def from_man_exp(man, exp, prec=None, rnd=round_fast): """Create raw mpf from (man, exp) pair. The mantissa may be signed. If no precision is specified, the mantissa is stored exactly.""" man = MPZ(man) sign = 0 if man < 0: sign = 1 man = -man if man < 1024: bc = bctable[int(man)] else: bc = bitcount(man) if not prec: if not man: return fzero if not man & 1: if man & 2: return (sign, man >> 1, exp + 1, bc - 1) t = trailtable[int(man & 255)] if not t: while not man & 255: man >>= 8 exp += 8 bc -= 8 t = trailtable[int(man & 255)] man >>= t exp += t bc -= t return (sign, man, exp, bc) return normalize(sign, man, exp, bc, prec, rnd) int_cache = dict((n, from_man_exp(n, 0)) for n in range(-10, 257)) if BACKEND == 'gmpy' and '_mpmath_create' in dir(gmpy): from_man_exp = gmpy._mpmath_create if BACKEND == 'sage': from_man_exp = sage_utils.from_man_exp def from_int(n, prec=0, rnd=round_fast): """Create a raw mpf from an integer. If no precision is specified, the mantissa is stored exactly.""" if not prec: if n in int_cache: return int_cache[n] return from_man_exp(n, 0, prec, rnd) def to_man_exp(s): """Return (man, exp) of a raw mpf. Raise an error if inf/nan.""" sign, man, exp, bc = s if (not man) and exp: raise ValueError("mantissa and exponent are undefined for %s" % man) return man, exp def to_int(s, rnd=None): """Convert a raw mpf to the nearest int. Rounding is done down by default (same as int(float) in Python), but can be changed. If the input is inf/nan, an exception is raised.""" sign, man, exp, bc = s if (not man) and exp: raise ValueError("cannot convert inf or nan to int") if exp >= 0: if sign: return (-man) << exp return man << exp # Make default rounding fast if not rnd: if sign: return -(man >> (-exp)) else: return man >> (-exp) if sign: return round_int(-man, -exp, rnd) else: return round_int(man, -exp, rnd) def mpf_round_int(s, rnd): sign, man, exp, bc = s if (not man) and exp: return s if exp >= 0: return s mag = exp+bc if mag < 1: if rnd == round_ceiling: if sign: return fzero else: return fone elif rnd == round_floor: if sign: return fnone else: return fzero elif rnd == round_nearest: if mag < 0 or man == MPZ_ONE: return fzero elif sign: return fnone else: return fone else: raise NotImplementedError return mpf_pos(s, min(bc, mag), rnd) def mpf_floor(s, prec=0, rnd=round_fast): v = mpf_round_int(s, round_floor) if prec: v = mpf_pos(v, prec, rnd) return v def mpf_ceil(s, prec=0, rnd=round_fast): v = mpf_round_int(s, round_ceiling) if prec: v = mpf_pos(v, prec, rnd) return v def mpf_nint(s, prec=0, rnd=round_fast): v = mpf_round_int(s, round_nearest) if prec: v = mpf_pos(v, prec, rnd) return v def mpf_frac(s, prec=0, rnd=round_fast): return mpf_sub(s, mpf_floor(s), prec, rnd) def from_float(x, prec=53, rnd=round_fast): """Create a raw mpf from a Python float, rounding if necessary. If prec >= 53, the result is guaranteed to represent exactly the same number as the input. If prec is not specified, use prec=53.""" # frexp only raises an exception for nan on some platforms if x != x: return fnan # in Python2.5 math.frexp gives an exception for float infinity # in Python2.6 it returns (float infinity, 0) try: m, e = math.frexp(x) except: if x == math_float_inf: return finf if x == -math_float_inf: return fninf return fnan if x == math_float_inf: return finf if x == -math_float_inf: return fninf return from_man_exp(int(m*(1<<53)), e-53, prec, rnd) def to_float(s, strict=False, rnd=round_fast): """ Convert a raw mpf to a Python float. The result is exact if the bitcount of s is <= 53 and no underflow/overflow occurs. If the number is too large or too small to represent as a regular float, it will be converted to inf or 0.0. Setting strict=True forces an OverflowError to be raised instead. Warning: with a directed rounding mode, the correct nearest representable floating-point number in the specified direction might not be computed in case of overflow or (gradual) underflow. """ sign, man, exp, bc = s if not man: if s == fzero: return 0.0 if s == finf: return math_float_inf if s == fninf: return -math_float_inf return math_float_inf/math_float_inf if bc > 53: sign, man, exp, bc = normalize1(sign, man, exp, bc, 53, rnd) if sign: man = -man try: return math.ldexp(man, exp) except OverflowError: if strict: raise # Overflow to infinity if exp + bc > 0: if sign: return -math_float_inf else: return math_float_inf # Underflow to zero return 0.0 def from_rational(p, q, prec, rnd=round_fast): """Create a raw mpf from a rational number p/q, round if necessary.""" return mpf_div(from_int(p), from_int(q), prec, rnd) def to_rational(s): """Convert a raw mpf to a rational number. Return integers (p, q) such that s = p/q exactly.""" sign, man, exp, bc = s if sign: man = -man if bc == -1: raise ValueError("cannot convert %s to a rational number" % man) if exp >= 0: return man * (1<<exp), 1 else: return man, 1<<(-exp) def to_fixed(s, prec): """Convert a raw mpf to a fixed-point big integer""" sign, man, exp, bc = s offset = exp + prec if sign: if offset >= 0: return (-man) << offset else: return (-man) >> (-offset) else: if offset >= 0: return man << offset else: return man >> (-offset) ############################################################################## ############################################################################## #----------------------------------------------------------------------------# # Arithmetic operations, etc. # #----------------------------------------------------------------------------# def mpf_rand(prec): """Return a raw mpf chosen randomly from [0, 1), with prec bits in the mantissa.""" global getrandbits if not getrandbits: import random getrandbits = random.getrandbits return from_man_exp(getrandbits(prec), -prec, prec, round_floor) def mpf_eq(s, t): """Test equality of two raw mpfs. This is simply tuple comparison unless either number is nan, in which case the result is False.""" if not s[1] or not t[1]: if s == fnan or t == fnan: return False return s == t def mpf_hash(s): # Duplicate the new hash algorithm introduces in Python 3.2. if sys.version >= "3.2": ssign, sman, sexp, sbc = s # Handle special numbers if not sman: if s == fnan: return sys.hash_info.nan if s == finf: return sys.hash_info.inf if s == fninf: return -sys.hash_info.inf h = sman % HASH_MODULUS if sexp >= 0: sexp = sexp % HASH_BITS else: sexp = HASH_BITS - 1 - ((-1 - sexp) % HASH_BITS) h = (h << sexp) % HASH_MODULUS if ssign: h = -h if h == -1: h == -2 return int(h) else: try: # Try to be compatible with hash values for floats and ints return hash(to_float(s, strict=1)) except OverflowError: # We must unfortunately sacrifice compatibility with ints here. # We could do hash(man << exp) when the exponent is positive, but # this would cause unreasonable inefficiency for large numbers. return hash(s) def mpf_cmp(s, t): """Compare the raw mpfs s and t. Return -1 if s < t, 0 if s == t, and 1 if s > t. (Same convention as Python's cmp() function.)""" # In principle, a comparison amounts to determining the sign of s-t. # A full subtraction is relatively slow, however, so we first try to # look at the components. ssign, sman, sexp, sbc = s tsign, tman, texp, tbc = t # Handle zeros and special numbers if not sman or not tman: if s == fzero: return -mpf_sign(t) if t == fzero: return mpf_sign(s) if s == t: return 0 # Follow same convention as Python's cmp for float nan if t == fnan: return 1 if s == finf: return 1 if t == fninf: return 1 return -1 # Different sides of zero if ssign != tsign: if not ssign: return 1 return -1 # This reduces to direct integer comparison if sexp == texp: if sman == tman: return 0 if sman > tman: if ssign: return -1 else: return 1 else: if ssign: return 1 else: return -1 # Check position of the highest set bit in each number. If # different, there is certainly an inequality. a = sbc + sexp b = tbc + texp if ssign: if a < b: return 1 if a > b: return -1 else: if a < b: return -1 if a > b: return 1 # Both numbers have the same highest bit. Subtract to find # how the lower bits compare. delta = mpf_sub(s, t, 5, round_floor) if delta[0]: return -1 return 1 def mpf_lt(s, t): if s == fnan or t == fnan: return False return mpf_cmp(s, t) < 0 def mpf_le(s, t): if s == fnan or t == fnan: return False return mpf_cmp(s, t) <= 0 def mpf_gt(s, t): if s == fnan or t == fnan: return False return mpf_cmp(s, t) > 0 def mpf_ge(s, t): if s == fnan or t == fnan: return False return mpf_cmp(s, t) >= 0 def mpf_min_max(seq): min = max = seq[0] for x in seq[1:]: if mpf_lt(x, min): min = x if mpf_gt(x, max): max = x return min, max def mpf_pos(s, prec=0, rnd=round_fast): """Calculate 0+s for a raw mpf (i.e., just round s to the specified precision).""" if prec: sign, man, exp, bc = s if (not man) and exp: return s return normalize1(sign, man, exp, bc, prec, rnd) return s def mpf_neg(s, prec=None, rnd=round_fast): """Negate a raw mpf (return -s), rounding the result to the specified precision. The prec argument can be omitted to do the operation exactly.""" sign, man, exp, bc = s if not man: if exp: if s == finf: return fninf if s == fninf: return finf return s if not prec: return (1-sign, man, exp, bc) return normalize1(1-sign, man, exp, bc, prec, rnd) def mpf_abs(s, prec=None, rnd=round_fast): """Return abs(s) of the raw mpf s, rounded to the specified precision. The prec argument can be omitted to generate an exact result.""" sign, man, exp, bc = s if (not man) and exp: if s == fninf: return finf return s if not prec: if sign: return (0, man, exp, bc) return s return normalize1(0, man, exp, bc, prec, rnd) def mpf_sign(s): """Return -1, 0, or 1 (as a Python int, not a raw mpf) depending on whether s is negative, zero, or positive. (Nan is taken to give 0.)""" sign, man, exp, bc = s if not man: if s == finf: return 1 if s == fninf: return -1 return 0 return (-1) ** sign def mpf_add(s, t, prec=0, rnd=round_fast, _sub=0): """ Add the two raw mpf values s and t. With prec=0, no rounding is performed. Note that this can produce a very large mantissa (potentially too large to fit in memory) if exponents are far apart. """ ssign, sman, sexp, sbc = s tsign, tman, texp, tbc = t tsign ^= _sub # Standard case: two nonzero, regular numbers if sman and tman: offset = sexp - texp if offset: if offset > 0: # Outside precision range; only need to perturb if offset > 100 and prec: delta = sbc + sexp - tbc - texp if delta > prec + 4: offset = prec + 4 sman <<= offset if tsign == ssign: sman += 1 else: sman -= 1 return normalize1(ssign, sman, sexp-offset, bitcount(sman), prec, rnd) # Add if ssign == tsign: man = tman + (sman << offset) # Subtract else: if ssign: man = tman - (sman << offset) else: man = (sman << offset) - tman if man >= 0: ssign = 0 else: man = -man ssign = 1 bc = bitcount(man) return normalize1(ssign, man, texp, bc, prec or bc, rnd) elif offset < 0: # Outside precision range; only need to perturb if offset < -100 and prec: delta = tbc + texp - sbc - sexp if delta > prec + 4: offset = prec + 4 tman <<= offset if ssign == tsign: tman += 1 else: tman -= 1 return normalize1(tsign, tman, texp-offset, bitcount(tman), prec, rnd) # Add if ssign == tsign: man = sman + (tman << -offset) # Subtract else: if tsign: man = sman - (tman << -offset) else: man = (tman << -offset) - sman if man >= 0: ssign = 0 else: man = -man ssign = 1 bc = bitcount(man) return normalize1(ssign, man, sexp, bc, prec or bc, rnd) # Equal exponents; no shifting necessary if ssign == tsign: man = tman + sman else: if ssign: man = tman - sman else: man = sman - tman if man >= 0: ssign = 0 else: man = -man ssign = 1 bc = bitcount(man) return normalize(ssign, man, texp, bc, prec or bc, rnd) # Handle zeros and special numbers if _sub: t = mpf_neg(t) if not sman: if sexp: if s == t or tman or not texp: return s return fnan if tman: return normalize1(tsign, tman, texp, tbc, prec or tbc, rnd) return t if texp: return t if sman: return normalize1(ssign, sman, sexp, sbc, prec or sbc, rnd) return s def mpf_sub(s, t, prec=0, rnd=round_fast): """Return the difference of two raw mpfs, s-t. This function is simply a wrapper of mpf_add that changes the sign of t.""" return mpf_add(s, t, prec, rnd, 1) def mpf_sum(xs, prec=0, rnd=round_fast, absolute=False): """ Sum a list of mpf values efficiently and accurately (typically no temporary roundoff occurs). If prec=0, the final result will not be rounded either. There may be roundoff error or cancellation if extremely large exponent differences occur. With absolute=True, sums the absolute values. """ man = 0 exp = 0 max_extra_prec = prec*2 or 1000000 # XXX special = None for x in xs: xsign, xman, xexp, xbc = x if xman: if xsign and not absolute: xman = -xman delta = xexp - exp if xexp >= exp: # x much larger than existing sum? # first: quick test if (delta > max_extra_prec) and \ ((not man) or delta-bitcount(abs(man)) > max_extra_prec): man = xman exp = xexp else: man += (xman << delta) else: delta = -delta # x much smaller than existing sum? if delta-xbc > max_extra_prec: if not man: man, exp = xman, xexp else: man = (man << delta) + xman exp = xexp elif xexp: if absolute: x = mpf_abs(x) special = mpf_add(special or fzero, x, 1) # Will be inf or nan if special: return special return from_man_exp(man, exp, prec, rnd) def gmpy_mpf_mul(s, t, prec=0, rnd=round_fast): """Multiply two raw mpfs""" ssign, sman, sexp, sbc = s tsign, tman, texp, tbc = t sign = ssign ^ tsign man = sman*tman if man: bc = bitcount(man) if prec: return normalize1(sign, man, sexp+texp, bc, prec, rnd) else: return (sign, man, sexp+texp, bc) s_special = (not sman) and sexp t_special = (not tman) and texp if not s_special and not t_special: return fzero if fnan in (s, t): return fnan if (not tman) and texp: s, t = t, s if t == fzero: return fnan return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)] def gmpy_mpf_mul_int(s, n, prec, rnd=round_fast): """Multiply by a Python integer.""" sign, man, exp, bc = s if not man: return mpf_mul(s, from_int(n), prec, rnd) if not n: return fzero if n < 0: sign ^= 1 n = -n man *= n return normalize(sign, man, exp, bitcount(man), prec, rnd) def python_mpf_mul(s, t, prec=0, rnd=round_fast): """Multiply two raw mpfs""" ssign, sman, sexp, sbc = s tsign, tman, texp, tbc = t sign = ssign ^ tsign man = sman*tman if man: bc = sbc + tbc - 1 bc += int(man>>bc) if prec: return normalize1(sign, man, sexp+texp, bc, prec, rnd) else: return (sign, man, sexp+texp, bc) s_special = (not sman) and sexp t_special = (not tman) and texp if not s_special and not t_special: return fzero if fnan in (s, t): return fnan if (not tman) and texp: s, t = t, s if t == fzero: return fnan return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)] def python_mpf_mul_int(s, n, prec, rnd=round_fast): """Multiply by a Python integer.""" sign, man, exp, bc = s if not man: return mpf_mul(s, from_int(n), prec, rnd) if not n: return fzero if n < 0: sign ^= 1 n = -n man *= n # Generally n will be small if n < 1024: bc += bctable[int(n)] - 1 else: bc += bitcount(n) - 1 bc += int(man>>bc) return normalize(sign, man, exp, bc, prec, rnd) if BACKEND == 'gmpy': mpf_mul = gmpy_mpf_mul mpf_mul_int = gmpy_mpf_mul_int else: mpf_mul = python_mpf_mul mpf_mul_int = python_mpf_mul_int def mpf_shift(s, n): """Quickly multiply the raw mpf s by 2**n without rounding.""" sign, man, exp, bc = s if not man: return s return sign, man, exp+n, bc def mpf_frexp(x): """Convert x = y*2**n to (y, n) with abs(y) in [0.5, 1) if nonzero""" sign, man, exp, bc = x if not man: if x == fzero: return (fzero, 0) else: raise ValueError return mpf_shift(x, -bc-exp), bc+exp def mpf_div(s, t, prec, rnd=round_fast): """Floating-point division""" ssign, sman, sexp, sbc = s tsign, tman, texp, tbc = t if not sman or not tman: if s == fzero: if t == fzero: raise ZeroDivisionError if t == fnan: return fnan return fzero if t == fzero: raise ZeroDivisionError s_special = (not sman) and sexp t_special = (not tman) and texp if s_special and t_special: return fnan if s == fnan or t == fnan: return fnan if not t_special: if t == fzero: return fnan return {1:finf, -1:fninf}[mpf_sign(s) * mpf_sign(t)] return fzero sign = ssign ^ tsign if tman == 1: return normalize1(sign, sman, sexp-texp, sbc, prec, rnd) # Same strategy as for addition: if there is a remainder, perturb # the result a few bits outside the precision range before rounding extra = prec - sbc + tbc + 5 if extra < 5: extra = 5 quot, rem = divmod(sman<<extra, tman) if rem: quot = (quot<<1) + 1 extra += 1 return normalize1(sign, quot, sexp-texp-extra, bitcount(quot), prec, rnd) return normalize(sign, quot, sexp-texp-extra, bitcount(quot), prec, rnd) def mpf_rdiv_int(n, t, prec, rnd=round_fast): """Floating-point division n/t with a Python integer as numerator""" sign, man, exp, bc = t if not n or not man: return mpf_div(from_int(n), t, prec, rnd) if n < 0: sign ^= 1 n = -n extra = prec + bc + 5 quot, rem = divmod(n<<extra, man) if rem: quot = (quot<<1) + 1 extra += 1 return normalize1(sign, quot, -exp-extra, bitcount(quot), prec, rnd) return normalize(sign, quot, -exp-extra, bitcount(quot), prec, rnd) def mpf_mod(s, t, prec, rnd=round_fast): ssign, sman, sexp, sbc = s tsign, tman, texp, tbc = t if ((not sman) and sexp) or ((not tman) and texp): return fnan # Important special case: do nothing if t is larger if ssign == tsign and texp > sexp+sbc: return s # Another important special case: this allows us to do e.g. x % 1.0 # to find the fractional part of x, and it will work when x is huge. if tman == 1 and sexp > texp+tbc: return fzero base = min(sexp, texp) sman = (-1)**ssign * sman tman = (-1)**tsign * tman man = (sman << (sexp-base)) % (tman << (texp-base)) if man >= 0: sign = 0 else: man = -man sign = 1 return normalize(sign, man, base, bitcount(man), prec, rnd) reciprocal_rnd = { round_down : round_up, round_up : round_down, round_floor : round_ceiling, round_ceiling : round_floor, round_nearest : round_nearest } negative_rnd = { round_down : round_down, round_up : round_up, round_floor : round_ceiling, round_ceiling : round_floor, round_nearest : round_nearest } def mpf_pow_int(s, n, prec, rnd=round_fast): """Compute s**n, where s is a raw mpf and n is a Python integer.""" sign, man, exp, bc = s if (not man) and exp: if s == finf: if n > 0: return s if n == 0: return fnan return fzero if s == fninf: if n > 0: return [finf, fninf][n & 1] if n == 0: return fnan return fzero return fnan n = int(n) if n == 0: return fone if n == 1: return mpf_pos(s, prec, rnd) if n == 2: _, man, exp, bc = s if not man: return fzero man = man*man if man == 1: return (0, MPZ_ONE, exp+exp, 1) bc = bc + bc - 2 bc += bctable[int(man>>bc)] return normalize1(0, man, exp+exp, bc, prec, rnd) if n == -1: return mpf_div(fone, s, prec, rnd) if n < 0: inverse = mpf_pow_int(s, -n, prec+5, reciprocal_rnd[rnd]) return mpf_div(fone, inverse, prec, rnd) result_sign = sign & n # Use exact integer power when the exact mantissa is small if man == 1: return (result_sign, MPZ_ONE, exp*n, 1) if bc*n < 1000: man **= n return normalize1(result_sign, man, exp*n, bitcount(man), prec, rnd) # Use directed rounding all the way through to maintain rigorous # bounds for interval arithmetic rounds_down = (rnd == round_nearest) or \ shifts_down[rnd][result_sign] # Now we perform binary exponentiation. Need to estimate precision # to avoid rounding errors from temporary operations. Roughly log_2(n) # operations are performed. workprec = prec + 4*bitcount(n) + 4 _, pm, pe, pbc = fone while 1: if n & 1: pm = pm*man pe = pe+exp pbc += bc - 2 pbc = pbc + bctable[int(pm >> pbc)] if pbc > workprec: if rounds_down: pm = pm >> (pbc-workprec) else: pm = -((-pm) >> (pbc-workprec)) pe += pbc - workprec pbc = workprec n -= 1 if not n: break man = man*man exp = exp+exp bc = bc + bc - 2 bc = bc + bctable[int(man >> bc)] if bc > workprec: if rounds_down: man = man >> (bc-workprec) else: man = -((-man) >> (bc-workprec)) exp += bc - workprec bc = workprec n = n // 2 return normalize(result_sign, pm, pe, pbc, prec, rnd) def mpf_perturb(x, eps_sign, prec, rnd): """ For nonzero x, calculate x + eps with directed rounding, where eps < prec relatively and eps has the given sign (0 for positive, 1 for negative). With rounding to nearest, this is taken to simply normalize x to the given precision. """ if rnd == round_nearest: return mpf_pos(x, prec, rnd) sign, man, exp, bc = x eps = (eps_sign, MPZ_ONE, exp+bc-prec-1, 1) if sign: away = (rnd in (round_down, round_ceiling)) ^ eps_sign else: away = (rnd in (round_up, round_ceiling)) ^ eps_sign if away: return mpf_add(x, eps, prec, rnd) else: return mpf_pos(x, prec, rnd) #----------------------------------------------------------------------------# # Radix conversion # #----------------------------------------------------------------------------# def to_digits_exp(s, dps): """Helper function for representing the floating-point number s as a decimal with dps digits. Returns (sign, string, exponent) where sign is '' or '-', string is the digit string, and exponent is the decimal exponent as an int. If inexact, the decimal representation is rounded toward zero.""" # Extract sign first so it doesn't mess up the string digit count if s[0]: sign = '-' s = mpf_neg(s) else: sign = '' _sign, man, exp, bc = s if not man: return '', '0', 0 bitprec = int(dps * math.log(10,2)) + 10 # Cut down to size # TODO: account for precision when doing this exp_from_1 = exp + bc if abs(exp_from_1) > 3500: from .libelefun import mpf_ln2, mpf_ln10 # Set b = int(exp * log(2)/log(10)) # If exp is huge, we must use high-precision arithmetic to # find the nearest power of ten expprec = bitcount(abs(exp)) + 5 tmp = from_int(exp) tmp = mpf_mul(tmp, mpf_ln2(expprec)) tmp = mpf_div(tmp, mpf_ln10(expprec), expprec) b = to_int(tmp) s = mpf_div(s, mpf_pow_int(ften, b, bitprec), bitprec) _sign, man, exp, bc = s exponent = b else: exponent = 0 # First, calculate mantissa digits by converting to a binary # fixed-point number and then converting that number to # a decimal fixed-point number. fixprec = max(bitprec - exp - bc, 0) fixdps = int(fixprec / math.log(10,2) + 0.5) sf = to_fixed(s, fixprec) sd = bin_to_radix(sf, fixprec, 10, fixdps) digits = numeral(sd, base=10, size=dps) exponent += len(digits) - fixdps - 1 return sign, digits, exponent def to_str(s, dps, strip_zeros=True, min_fixed=None, max_fixed=None, show_zero_exponent=False): """ Convert a raw mpf to a decimal floating-point literal with at most `dps` decimal digits in the mantissa (not counting extra zeros that may be inserted for visual purposes). The number will be printed in fixed-point format if the position of the leading digit is strictly between min_fixed (default = min(-dps/3,-5)) and max_fixed (default = dps). To force fixed-point format always, set min_fixed = -inf, max_fixed = +inf. To force floating-point format, set min_fixed >= max_fixed. The literal is formatted so that it can be parsed back to a number by to_str, float() or Decimal(). """ # Special numbers if not s[1]: if s == fzero: if dps: t = '0.0' else: t = '.0' if show_zero_exponent: t += 'e+0' return t if s == finf: return '+inf' if s == fninf: return '-inf' if s == fnan: return 'nan' raise ValueError if min_fixed is None: min_fixed = min(-(dps//3), -5) if max_fixed is None: max_fixed = dps # to_digits_exp rounds to floor. # This sometimes kills some instances of "...00001" sign, digits, exponent = to_digits_exp(s, dps+3) # No digits: show only .0; round exponent to nearest if not dps: if digits[0] in '56789': exponent += 1 digits = ".0" else: # Rounding up kills some instances of "...99999" if len(digits) > dps and digits[dps] in '56789' and \ (dps < 500 or digits[dps-4:dps] == '9999'): digits2 = str(int(digits[:dps]) + 1) if len(digits2) > dps: digits2 = digits2[:dps] exponent += 1 digits = digits2 else: digits = digits[:dps] # Prettify numbers close to unit magnitude if min_fixed < exponent < max_fixed: if exponent < 0: digits = ("0"*int(-exponent)) + digits split = 1 else: split = exponent + 1 if split > dps: digits += "0"*(split-dps) exponent = 0 else: split = 1 digits = (digits[:split] + "." + digits[split:]) if strip_zeros: # Clean up trailing zeros digits = digits.rstrip('0') if digits[-1] == ".": digits += "0" if exponent == 0 and dps and not show_zero_exponent: return sign + digits if exponent >= 0: return sign + digits + "e+" + str(exponent) if exponent < 0: return sign + digits + "e" + str(exponent) def str_to_man_exp(x, base=10): """Helper function for from_str.""" # Verify that the input is a valid float literal float(x) # Split into mantissa, exponent x = x.lower() parts = x.split('e') if len(parts) == 1: exp = 0 else: # == 2 x = parts[0] exp = int(parts[1]) # Look for radix point in mantissa parts = x.split('.') if len(parts) == 2: a, b = parts[0], parts[1].rstrip('0') exp -= len(b) x = a + b x = MPZ(int(x, base)) return x, exp special_str = {'inf':finf, '+inf':finf, '-inf':fninf, 'nan':fnan} def from_str(x, prec, rnd=round_fast): """Create a raw mpf from a decimal literal, rounding in the specified direction if the input number cannot be represented exactly as a binary floating-point number with the given number of bits. The literal syntax accepted is the same as for Python floats. TODO: the rounding does not work properly for large exponents. """ x = x.strip() if x in special_str: return special_str[x] if '/' in x: p, q = x.split('/') return from_rational(int(p), int(q), prec, rnd) man, exp = str_to_man_exp(x, base=10) # XXX: appropriate cutoffs & track direction # note no factors of 5 if abs(exp) > 400: s = from_int(man, prec+10) s = mpf_mul(s, mpf_pow_int(ften, exp, prec+10), prec, rnd) else: if exp >= 0: s = from_int(man * 10**exp, prec, rnd) else: s = from_rational(man, 10**-exp, prec, rnd) return s # Binary string conversion. These are currently mainly used for debugging # and could use some improvement in the future def from_bstr(x): man, exp = str_to_man_exp(x, base=2) man = MPZ(man) sign = 0 if man < 0: man = -man sign = 1 bc = bitcount(man) return normalize(sign, man, exp, bc, bc, round_floor) def to_bstr(x): sign, man, exp, bc = x return ['','-'][sign] + numeral(man, size=bitcount(man), base=2) + ("e%i" % exp) #----------------------------------------------------------------------------# # Square roots # #----------------------------------------------------------------------------# def mpf_sqrt(s, prec, rnd=round_fast): """ Compute the square root of a nonnegative mpf value. The result is correctly rounded. """ sign, man, exp, bc = s if sign: raise ComplexResult("square root of a negative number") if not man: return s if exp & 1: exp -= 1 man <<= 1 bc += 1 elif man == 1: return normalize1(sign, man, exp//2, bc, prec, rnd) shift = max(4, 2*prec-bc+4) shift += shift & 1 if rnd in 'fd': man = isqrt(man<<shift) else: man, rem = sqrtrem(man<<shift) # Perturb up if rem: man = (man<<1)+1 shift += 2 return from_man_exp(man, (exp-shift)//2, prec, rnd) def mpf_hypot(x, y, prec, rnd=round_fast): """Compute the Euclidean norm sqrt(x**2 + y**2) of two raw mpfs x and y.""" if y == fzero: return mpf_abs(x, prec, rnd) if x == fzero: return mpf_abs(y, prec, rnd) hypot2 = mpf_add(mpf_mul(x,x), mpf_mul(y,y), prec+4) return mpf_sqrt(hypot2, prec, rnd) if BACKEND == 'sage': try: import sage.libs.mpmath.ext_libmp as ext_lib mpf_add = ext_lib.mpf_add mpf_sub = ext_lib.mpf_sub mpf_mul = ext_lib.mpf_mul mpf_div = ext_lib.mpf_div mpf_sqrt = ext_lib.mpf_sqrt except ImportError: pass
43,833
30.626263
84
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/gammazeta.py
""" ----------------------------------------------------------------------- This module implements gamma- and zeta-related functions: * Bernoulli numbers * Factorials * The gamma function * Polygamma functions * Harmonic numbers * The Riemann zeta function * Constants related to these functions ----------------------------------------------------------------------- """ import math import sys from .backend import xrange from .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_THREE, gmpy from .libintmath import list_primes, ifac, ifac2, moebius from .libmpf import (\ round_floor, round_ceiling, round_down, round_up, round_nearest, round_fast, lshift, sqrt_fixed, isqrt_fast, fzero, fone, fnone, fhalf, ftwo, finf, fninf, fnan, from_int, to_int, to_fixed, from_man_exp, from_rational, mpf_pos, mpf_neg, mpf_abs, mpf_add, mpf_sub, mpf_mul, mpf_mul_int, mpf_div, mpf_sqrt, mpf_pow_int, mpf_rdiv_int, mpf_perturb, mpf_le, mpf_lt, mpf_gt, mpf_shift, negative_rnd, reciprocal_rnd, bitcount, to_float, mpf_floor, mpf_sign, ComplexResult ) from .libelefun import (\ constant_memo, def_mpf_constant, mpf_pi, pi_fixed, ln2_fixed, log_int_fixed, mpf_ln2, mpf_exp, mpf_log, mpf_pow, mpf_cosh, mpf_cos_sin, mpf_cosh_sinh, mpf_cos_sin_pi, mpf_cos_pi, mpf_sin_pi, ln_sqrt2pi_fixed, mpf_ln_sqrt2pi, sqrtpi_fixed, mpf_sqrtpi, cos_sin_fixed, exp_fixed ) from .libmpc import (\ mpc_zero, mpc_one, mpc_half, mpc_two, mpc_abs, mpc_shift, mpc_pos, mpc_neg, mpc_add, mpc_sub, mpc_mul, mpc_div, mpc_add_mpf, mpc_mul_mpf, mpc_div_mpf, mpc_mpf_div, mpc_mul_int, mpc_pow_int, mpc_log, mpc_exp, mpc_pow, mpc_cos_pi, mpc_sin_pi, mpc_reciprocal, mpc_square, mpc_sub_mpf ) # Catalan's constant is computed using Lupas's rapidly convergent series # (listed on http://mathworld.wolfram.com/CatalansConstant.html) # oo # ___ n-1 8n 2 3 2 # 1 \ (-1) 2 (40n - 24n + 3) [(2n)!] (n!) # K = --- ) ----------------------------------------- # 64 /___ 3 2 # n (2n-1) [(4n)!] # n = 1 @constant_memo def catalan_fixed(prec): prec = prec + 20 a = one = MPZ_ONE << prec s, t, n = 0, 1, 1 while t: a *= 32 * n**3 * (2*n-1) a //= (3-16*n+16*n**2)**2 t = a * (-1)**(n-1) * (40*n**2-24*n+3) // (n**3 * (2*n-1)) s += t n += 1 return s >> (20 + 6) # Khinchin's constant is relatively difficult to compute. Here # we use the rational zeta series # oo 2*n-1 # ___ ___ # \ ` zeta(2*n)-1 \ ` (-1)^(k+1) # log(K)*log(2) = ) ------------ ) ---------- # /___. n /___. k # n = 1 k = 1 # which adds half a digit per term. The essential trick for achieving # reasonable efficiency is to recycle both the values of the zeta # function (essentially Bernoulli numbers) and the partial terms of # the inner sum. # An alternative might be to use K = 2*exp[1/log(2) X] where # / 1 1 [ pi*x*(1-x^2) ] # X = | ------ log [ ------------ ]. # / 0 x(1+x) [ sin(pi*x) ] # and integrate numerically. In practice, this seems to be slightly # slower than the zeta series at high precision. @constant_memo def khinchin_fixed(prec): wp = int(prec + prec**0.5 + 15) s = MPZ_ZERO fac = from_int(4) t = ONE = MPZ_ONE << wp pi = mpf_pi(wp) pipow = twopi2 = mpf_shift(mpf_mul(pi, pi, wp), 2) n = 1 while 1: zeta2n = mpf_abs(mpf_bernoulli(2*n, wp)) zeta2n = mpf_mul(zeta2n, pipow, wp) zeta2n = mpf_div(zeta2n, fac, wp) zeta2n = to_fixed(zeta2n, wp) term = (((zeta2n - ONE) * t) // n) >> wp if term < 100: break #if not n % 10: # print n, math.log(int(abs(term))) s += term t += ONE//(2*n+1) - ONE//(2*n) n += 1 fac = mpf_mul_int(fac, (2*n)*(2*n-1), wp) pipow = mpf_mul(pipow, twopi2, wp) s = (s << wp) // ln2_fixed(wp) K = mpf_exp(from_man_exp(s, -wp), wp) K = to_fixed(K, prec) return K # Glaisher's constant is defined as A = exp(1/2 - zeta'(-1)). # One way to compute it would be to perform direct numerical # differentiation, but computing arbitrary Riemann zeta function # values at high precision is expensive. We instead use the formula # A = exp((6 (-zeta'(2))/pi^2 + log 2 pi + gamma)/12) # and compute zeta'(2) from the series representation # oo # ___ # \ log k # -zeta'(2) = ) ----- # /___ 2 # k # k = 2 # This series converges exceptionally slowly, but can be accelerated # using Euler-Maclaurin formula. The important insight is that the # E-M integral can be done in closed form and that the high order # are given by # n / \ # d | log x | a + b log x # --- | ----- | = ----------- # n | 2 | 2 + n # dx \ x / x # where a and b are integers given by a simple recurrence. Note # that just one logarithm is needed. However, lots of integer # logarithms are required for the initial summation. # This algorithm could possibly be turned into a faster algorithm # for general evaluation of zeta(s) or zeta'(s); this should be # looked into. @constant_memo def glaisher_fixed(prec): wp = prec + 30 # Number of direct terms to sum before applying the Euler-Maclaurin # formula to the tail. TODO: choose more intelligently N = int(0.33*prec + 5) ONE = MPZ_ONE << wp # Euler-Maclaurin, step 1: sum log(k)/k**2 for k from 2 to N-1 s = MPZ_ZERO for k in range(2, N): #print k, N s += log_int_fixed(k, wp) // k**2 logN = log_int_fixed(N, wp) #logN = to_fixed(mpf_log(from_int(N), wp+20), wp) # E-M step 2: integral of log(x)/x**2 from N to inf s += (ONE + logN) // N # E-M step 3: endpoint correction term f(N)/2 s += logN // (N**2 * 2) # E-M step 4: the series of derivatives pN = N**3 a = 1 b = -2 j = 3 fac = from_int(2) k = 1 while 1: # D(2*k-1) * B(2*k) / fac(2*k) [D(n) = nth derivative] D = ((a << wp) + b*logN) // pN D = from_man_exp(D, -wp) B = mpf_bernoulli(2*k, wp) term = mpf_mul(B, D, wp) term = mpf_div(term, fac, wp) term = to_fixed(term, wp) if abs(term) < 100: break #if not k % 10: # print k, math.log(int(abs(term)), 10) s -= term # Advance derivative twice a, b, pN, j = b-a*j, -j*b, pN*N, j+1 a, b, pN, j = b-a*j, -j*b, pN*N, j+1 k += 1 fac = mpf_mul_int(fac, (2*k)*(2*k-1), wp) # A = exp((6*s/pi**2 + log(2*pi) + euler)/12) pi = pi_fixed(wp) s *= 6 s = (s << wp) // (pi**2 >> wp) s += euler_fixed(wp) s += to_fixed(mpf_log(from_man_exp(2*pi, -wp), wp), wp) s //= 12 A = mpf_exp(from_man_exp(s, -wp), wp) return to_fixed(A, prec) # Apery's constant can be computed using the very rapidly convergent # series # oo # ___ 2 10 # \ n 205 n + 250 n + 77 (n!) # zeta(3) = ) (-1) ------------------- ---------- # /___ 64 5 # n = 0 ((2n+1)!) @constant_memo def apery_fixed(prec): prec += 20 d = MPZ_ONE << prec term = MPZ(77) << prec n = 1 s = MPZ_ZERO while term: s += term d *= (n**10) d //= (((2*n+1)**5) * (2*n)**5) term = (-1)**n * (205*(n**2) + 250*n + 77) * d n += 1 return s >> (20 + 6) """ Euler's constant (gamma) is computed using the Brent-McMillan formula, gamma ~= I(n)/J(n) - log(n), where I(n) = sum_{k=0,1,2,...} (n**k / k!)**2 * H(k) J(n) = sum_{k=0,1,2,...} (n**k / k!)**2 H(k) = 1 + 1/2 + 1/3 + ... + 1/k The error is bounded by O(exp(-4n)). Choosing n to be a power of two, 2**p, the logarithm becomes particularly easy to calculate.[1] We use the formulation of Algorithm 3.9 in [2] to make the summation more efficient. Reference: [1] Xavier Gourdon & Pascal Sebah, The Euler constant: gamma http://numbers.computation.free.fr/Constants/Gamma/gamma.pdf [2] Jonathan Borwein & David Bailey, Mathematics by Experiment, A K Peters, 2003 """ @constant_memo def euler_fixed(prec): extra = 30 prec += extra # choose p such that exp(-4*(2**p)) < 2**-n p = int(math.log((prec/4) * math.log(2), 2)) + 1 n = 2**p A = U = -p*ln2_fixed(prec) B = V = MPZ_ONE << prec k = 1 while 1: B = B*n**2//k**2 A = (A*n**2//k + B)//k U += A V += B if max(abs(A), abs(B)) < 100: break k += 1 return (U<<(prec-extra))//V # Use zeta accelerated formulas for the Mertens and twin # prime constants; see # http://mathworld.wolfram.com/MertensConstant.html # http://mathworld.wolfram.com/TwinPrimesConstant.html @constant_memo def mertens_fixed(prec): wp = prec + 20 m = 2 s = mpf_euler(wp) while 1: t = mpf_zeta_int(m, wp) if t == fone: break t = mpf_log(t, wp) t = mpf_mul_int(t, moebius(m), wp) t = mpf_div(t, from_int(m), wp) s = mpf_add(s, t) m += 1 return to_fixed(s, prec) @constant_memo def twinprime_fixed(prec): def I(n): return sum(moebius(d)<<(n//d) for d in xrange(1,n+1) if not n%d)//n wp = 2*prec + 30 res = fone primes = [from_rational(1,p,wp) for p in [2,3,5,7]] ppowers = [mpf_mul(p,p,wp) for p in primes] n = 2 while 1: a = mpf_zeta_int(n, wp) for i in range(4): a = mpf_mul(a, mpf_sub(fone, ppowers[i]), wp) ppowers[i] = mpf_mul(ppowers[i], primes[i], wp) a = mpf_pow_int(a, -I(n), wp) if mpf_pos(a, prec+10, 'n') == fone: break #from libmpf import to_str #print n, to_str(mpf_sub(fone, a), 6) res = mpf_mul(res, a, wp) n += 1 res = mpf_mul(res, from_int(3*15*35), wp) res = mpf_div(res, from_int(4*16*36), wp) return to_fixed(res, prec) mpf_euler = def_mpf_constant(euler_fixed) mpf_apery = def_mpf_constant(apery_fixed) mpf_khinchin = def_mpf_constant(khinchin_fixed) mpf_glaisher = def_mpf_constant(glaisher_fixed) mpf_catalan = def_mpf_constant(catalan_fixed) mpf_mertens = def_mpf_constant(mertens_fixed) mpf_twinprime = def_mpf_constant(twinprime_fixed) #-----------------------------------------------------------------------# # # # Bernoulli numbers # # # #-----------------------------------------------------------------------# MAX_BERNOULLI_CACHE = 3000 """ Small Bernoulli numbers and factorials are used in numerous summations, so it is critical for speed that sequential computation is fast and that values are cached up to a fairly high threshold. On the other hand, we also want to support fast computation of isolated large numbers. Currently, no such acceleration is provided for integer factorials (though it is for large floating-point factorials, which are computed via gamma if the precision is low enough). For sequential computation of Bernoulli numbers, we use Ramanujan's formula / n + 3 \ B = (A(n) - S(n)) / | | n \ n / where A(n) = (n+3)/3 when n = 0 or 2 (mod 6), A(n) = -(n+3)/6 when n = 4 (mod 6), and [n/6] ___ \ / n + 3 \ S(n) = ) | | * B /___ \ n - 6*k / n-6*k k = 1 For isolated large Bernoulli numbers, we use the Riemann zeta function to calculate a numerical value for B_n. The von Staudt-Clausen theorem can then be used to optionally find the exact value of the numerator and denominator. """ bernoulli_cache = {} f3 = from_int(3) f6 = from_int(6) def bernoulli_size(n): """Accurately estimate the size of B_n (even n > 2 only)""" lgn = math.log(n,2) return int(2.326 + 0.5*lgn + n*(lgn - 4.094)) BERNOULLI_PREC_CUTOFF = bernoulli_size(MAX_BERNOULLI_CACHE) def mpf_bernoulli(n, prec, rnd=None): """Computation of Bernoulli numbers (numerically)""" if n < 2: if n < 0: raise ValueError("Bernoulli numbers only defined for n >= 0") if n == 0: return fone if n == 1: return mpf_neg(fhalf) # For odd n > 1, the Bernoulli numbers are zero if n & 1: return fzero # If precision is extremely high, we can save time by computing # the Bernoulli number at a lower precision that is sufficient to # obtain the exact fraction, round to the exact fraction, and # convert the fraction back to an mpf value at the original precision if prec > BERNOULLI_PREC_CUTOFF and prec > bernoulli_size(n)*1.1 + 1000: p, q = bernfrac(n) return from_rational(p, q, prec, rnd or round_floor) if n > MAX_BERNOULLI_CACHE: return mpf_bernoulli_huge(n, prec, rnd) wp = prec + 30 # Reuse nearby precisions wp += 32 - (prec & 31) cached = bernoulli_cache.get(wp) if cached: numbers, state = cached if n in numbers: if not rnd: return numbers[n] return mpf_pos(numbers[n], prec, rnd) m, bin, bin1 = state if n - m > 10: return mpf_bernoulli_huge(n, prec, rnd) else: if n > 10: return mpf_bernoulli_huge(n, prec, rnd) numbers = {0:fone} m, bin, bin1 = state = [2, MPZ(10), MPZ_ONE] bernoulli_cache[wp] = (numbers, state) while m <= n: #print m case = m % 6 # Accurately estimate size of B_m so we can use # fixed point math without using too much precision szbm = bernoulli_size(m) s = 0 sexp = max(0, szbm) - wp if m < 6: a = MPZ_ZERO else: a = bin1 for j in xrange(1, m//6+1): usign, uman, uexp, ubc = u = numbers[m-6*j] if usign: uman = -uman s += lshift(a*uman, uexp-sexp) # Update inner binomial coefficient j6 = 6*j a *= ((m-5-j6)*(m-4-j6)*(m-3-j6)*(m-2-j6)*(m-1-j6)*(m-j6)) a //= ((4+j6)*(5+j6)*(6+j6)*(7+j6)*(8+j6)*(9+j6)) if case == 0: b = mpf_rdiv_int(m+3, f3, wp) if case == 2: b = mpf_rdiv_int(m+3, f3, wp) if case == 4: b = mpf_rdiv_int(-m-3, f6, wp) s = from_man_exp(s, sexp, wp) b = mpf_div(mpf_sub(b, s, wp), from_int(bin), wp) numbers[m] = b m += 2 # Update outer binomial coefficient bin = bin * ((m+2)*(m+3)) // (m*(m-1)) if m > 6: bin1 = bin1 * ((2+m)*(3+m)) // ((m-7)*(m-6)) state[:] = [m, bin, bin1] return numbers[n] def mpf_bernoulli_huge(n, prec, rnd=None): wp = prec + 10 piprec = wp + int(math.log(n,2)) v = mpf_gamma_int(n+1, wp) v = mpf_mul(v, mpf_zeta_int(n, wp), wp) v = mpf_mul(v, mpf_pow_int(mpf_pi(piprec), -n, wp)) v = mpf_shift(v, 1-n) if not n & 3: v = mpf_neg(v) return mpf_pos(v, prec, rnd or round_fast) def bernfrac(n): r""" Returns a tuple of integers `(p, q)` such that `p/q = B_n` exactly, where `B_n` denotes the `n`-th Bernoulli number. The fraction is always reduced to lowest terms. Note that for `n > 1` and `n` odd, `B_n = 0`, and `(0, 1)` is returned. **Examples** The first few Bernoulli numbers are exactly:: >>> from mpmath import * >>> for n in range(15): ... p, q = bernfrac(n) ... print("%s %s/%s" % (n, p, q)) ... 0 1/1 1 -1/2 2 1/6 3 0/1 4 -1/30 5 0/1 6 1/42 7 0/1 8 -1/30 9 0/1 10 5/66 11 0/1 12 -691/2730 13 0/1 14 7/6 This function works for arbitrarily large `n`:: >>> p, q = bernfrac(10**4) >>> print(q) 2338224387510 >>> print(len(str(p))) 27692 >>> mp.dps = 15 >>> print(mpf(p) / q) -9.04942396360948e+27677 >>> print(bernoulli(10**4)) -9.04942396360948e+27677 .. note :: :func:`~mpmath.bernoulli` computes a floating-point approximation directly, without computing the exact fraction first. This is much faster for large `n`. **Algorithm** :func:`~mpmath.bernfrac` works by computing the value of `B_n` numerically and then using the von Staudt-Clausen theorem [1] to reconstruct the exact fraction. For large `n`, this is significantly faster than computing `B_1, B_2, \ldots, B_2` recursively with exact arithmetic. The implementation has been tested for `n = 10^m` up to `m = 6`. In practice, :func:`~mpmath.bernfrac` appears to be about three times slower than the specialized program calcbn.exe [2] **References** 1. MathWorld, von Staudt-Clausen Theorem: http://mathworld.wolfram.com/vonStaudt-ClausenTheorem.html 2. The Bernoulli Number Page: http://www.bernoulli.org/ """ n = int(n) if n < 3: return [(1, 1), (-1, 2), (1, 6)][n] if n & 1: return (0, 1) q = 1 for k in list_primes(n+1): if not (n % (k-1)): q *= k prec = bernoulli_size(n) + int(math.log(q,2)) + 20 b = mpf_bernoulli(n, prec) p = mpf_mul(b, from_int(q)) pint = to_int(p, round_nearest) return (pint, q) #-----------------------------------------------------------------------# # # # The gamma function (OLD IMPLEMENTATION) # # # #-----------------------------------------------------------------------# """ We compute the real factorial / gamma function using Spouge's approximation x! = (x+a)**(x+1/2) * exp(-x-a) * [c_0 + S(x) + eps] where S(x) is the sum of c_k/(x+k) from k = 1 to a-1 and the coefficients are given by c_0 = sqrt(2*pi) (-1)**(k-1) c_k = ----------- (a-k)**(k-1/2) exp(-k+a), k = 1,2,...,a-1 (k - 1)! As proved by Spouge, if we choose a = log(2)/log(2*pi)*n = 0.38*n, the relative error eps is less than 2^(-n) for any x in the right complex half-plane (assuming a > 2). In practice, it seems that a can be chosen quite a bit lower still (30-50%); this possibility should be investigated. For negative x, we use the reflection formula. References: ----------- John L. Spouge, "Computation of the gamma, digamma, and trigamma functions", SIAM Journal on Numerical Analysis 31 (1994), no. 3, 931-944. """ spouge_cache = {} def calc_spouge_coefficients(a, prec): wp = prec + int(a*1.4) c = [0] * a # b = exp(a-1) b = mpf_exp(from_int(a-1), wp) # e = exp(1) e = mpf_exp(fone, wp) # sqrt(2*pi) sq2pi = mpf_sqrt(mpf_shift(mpf_pi(wp), 1), wp) c[0] = to_fixed(sq2pi, prec) for k in xrange(1, a): # c[k] = ((-1)**(k-1) * (a-k)**k) * b / sqrt(a-k) term = mpf_mul_int(b, ((-1)**(k-1) * (a-k)**k), wp) term = mpf_div(term, mpf_sqrt(from_int(a-k), wp), wp) c[k] = to_fixed(term, prec) # b = b / (e * k) b = mpf_div(b, mpf_mul(e, from_int(k), wp), wp) return c # Cached lookup of coefficients def get_spouge_coefficients(prec): # This exact precision has been used before if prec in spouge_cache: return spouge_cache[prec] for p in spouge_cache: if 0.8 <= prec/float(p) < 1: return spouge_cache[p] # Here we estimate the value of a based on Spouge's inequality for # the relative error a = max(3, int(0.38*prec)) # 0.38 = log(2)/log(2*pi), ~= 1.26*n coefs = calc_spouge_coefficients(a, prec) spouge_cache[prec] = (prec, a, coefs) return spouge_cache[prec] def spouge_sum_real(x, prec, a, c): x = to_fixed(x, prec) s = c[0] for k in xrange(1, a): s += (c[k] << prec) // (x + (k << prec)) return from_man_exp(s, -prec, prec, round_floor) # Unused: for fast computation of gamma(p/q) def spouge_sum_rational(p, q, prec, a, c): s = c[0] for k in xrange(1, a): s += c[k] * q // (p+q*k) return from_man_exp(s, -prec, prec, round_floor) # For a complex number a + b*I, we have # # c_k (a+k)*c_k b * c_k # ------------- = --------- - ------- * I # (a + b*I) + k M M # # 2 2 2 2 2 # where M = (a+k) + b = (a + b ) + (2*a*k + k ) def spouge_sum_complex(re, im, prec, a, c): re = to_fixed(re, prec) im = to_fixed(im, prec) sre, sim = c[0], 0 mag = ((re**2)>>prec) + ((im**2)>>prec) for k in xrange(1, a): M = mag + re*(2*k) + ((k**2) << prec) sre += (c[k] * (re + (k << prec))) // M sim -= (c[k] * im) // M re = from_man_exp(sre, -prec, prec, round_floor) im = from_man_exp(sim, -prec, prec, round_floor) return re, im def mpf_gamma_int_old(n, prec, rounding=round_fast): if n < 1000: return from_int(ifac(n-1), prec, rounding) # XXX: choose the cutoff less arbitrarily size = int(n*math.log(n,2)) if prec > size/20.0: return from_int(ifac(n-1), prec, rounding) return mpf_gamma(from_int(n), prec, rounding) def mpf_factorial_old(x, prec, rounding=round_fast): return mpf_gamma_old(x, prec, rounding, p1=0) def mpc_factorial_old(x, prec, rounding=round_fast): return mpc_gamma_old(x, prec, rounding, p1=0) def mpf_gamma_old(x, prec, rounding=round_fast, p1=1): """ Computes the gamma function of a real floating-point argument. With p1=0, computes a factorial instead. """ sign, man, exp, bc = x if not man: if x == finf: return finf if x == fninf or x == fnan: return fnan # More precision is needed for enormous x. TODO: # use Stirling's formula + Euler-Maclaurin summation size = exp + bc if size > 5: size = int(size * math.log(size,2)) wp = prec + max(0, size) + 15 if exp >= 0: if sign or (p1 and not man): raise ValueError("gamma function pole") # A direct factorial is fastest if exp + bc <= 10: return from_int(ifac((man<<exp)-p1), prec, rounding) reflect = sign or exp+bc < -1 if p1: # Should be done exactly! x = mpf_sub(x, fone) # x < 0.25 if reflect: # gamma = pi / (sin(pi*x) * gamma(1-x)) wp += 15 pix = mpf_mul(x, mpf_pi(wp), wp) t = mpf_sin_pi(x, wp) g = mpf_gamma_old(mpf_sub(fone, x), wp) return mpf_div(pix, mpf_mul(t, g, wp), prec, rounding) sprec, a, c = get_spouge_coefficients(wp) s = spouge_sum_real(x, sprec, a, c) # gamma = exp(log(x+a)*(x+0.5) - xpa) * s xpa = mpf_add(x, from_int(a), wp) logxpa = mpf_log(xpa, wp) xph = mpf_add(x, fhalf, wp) t = mpf_sub(mpf_mul(logxpa, xph, wp), xpa, wp) t = mpf_mul(mpf_exp(t, wp), s, prec, rounding) return t def mpc_gamma_old(x, prec, rounding=round_fast, p1=1): re, im = x if im == fzero: return mpf_gamma_old(re, prec, rounding, p1), fzero # More precision is needed for enormous x. sign, man, exp, bc = re isign, iman, iexp, ibc = im if re == fzero: size = iexp+ibc else: size = max(exp+bc, iexp+ibc) if size > 5: size = int(size * math.log(size,2)) reflect = sign or (exp+bc < -1) wp = prec + max(0, size) + 25 # Near x = 0 pole (TODO: other poles) if p1: if size < -prec-5: return mpc_add_mpf(mpc_div(mpc_one, x, 2*prec+10), \ mpf_neg(mpf_euler(2*prec+10)), prec, rounding) elif size < -5: wp += (-2*size) if p1: # Should be done exactly! re_orig = re re = mpf_sub(re, fone, bc+abs(exp)+2) x = re, im if reflect: # Reflection formula wp += 15 pi = mpf_pi(wp), fzero pix = mpc_mul(x, pi, wp) t = mpc_sin_pi(x, wp) u = mpc_sub(mpc_one, x, wp) g = mpc_gamma_old(u, wp) w = mpc_mul(t, g, wp) return mpc_div(pix, w, wp) # Extremely close to the real line? # XXX: reflection formula if iexp+ibc < -wp: a = mpf_gamma_old(re_orig, wp) b = mpf_psi0(re_orig, wp) gamma_diff = mpf_div(a, b, wp) return mpf_pos(a, prec, rounding), mpf_mul(gamma_diff, im, prec, rounding) sprec, a, c = get_spouge_coefficients(wp) s = spouge_sum_complex(re, im, sprec, a, c) # gamma = exp(log(x+a)*(x+0.5) - xpa) * s repa = mpf_add(re, from_int(a), wp) logxpa = mpc_log((repa, im), wp) reph = mpf_add(re, fhalf, wp) t = mpc_sub(mpc_mul(logxpa, (reph, im), wp), (repa, im), wp) t = mpc_mul(mpc_exp(t, wp), s, prec, rounding) return t #-----------------------------------------------------------------------# # # # Polygamma functions # # # #-----------------------------------------------------------------------# """ For all polygamma (psi) functions, we use the Euler-Maclaurin summation formula. It looks slightly different in the m = 0 and m > 0 cases. For m = 0, we have oo ___ B (0) 1 \ 2 k -2 k psi (z) ~ log z + --- - ) ------ z 2 z /___ (2 k)! k = 1 Experiment shows that the minimum term of the asymptotic series reaches 2^(-p) when Re(z) > 0.11*p. So we simply use the recurrence for psi (equivalent, in fact, to summing to the first few terms directly before applying E-M) to obtain z large enough. Since, very crudely, log z ~= 1 for Re(z) > 1, we can use fixed-point arithmetic (if z is extremely large, log(z) itself is a sufficient approximation, so we can stop there already). For Re(z) << 0, we could use recurrence, but this is of course inefficient for large negative z, so there we use the reflection formula instead. For m > 0, we have N - 1 ___ ~~~(m) [ \ 1 ] 1 1 psi (z) ~ [ ) -------- ] + ---------- + -------- + [ /___ m+1 ] m+1 m k = 1 (z+k) ] 2 (z+N) m (z+N) oo ___ B \ 2 k (m+1) (m+2) ... (m+2k-1) + ) ------ ------------------------ /___ (2 k)! m + 2 k k = 1 (z+N) where ~~~ denotes the function rescaled by 1/((-1)^(m+1) m!). Here again N is chosen to make z+N large enough for the minimum term in the last series to become smaller than eps. TODO: the current estimation of N for m > 0 is *very suboptimal*. TODO: implement the reflection formula for m > 0, Re(z) << 0. It is generally a combination of multiple cotangents. Need to figure out a reasonably simple way to generate these formulas on the fly. TODO: maybe use exact algorithms to compute psi for integral and certain rational arguments, as this can be much more efficient. (On the other hand, the availability of these special values provides a convenient way to test the general algorithm.) """ # Harmonic numbers are just shifted digamma functions # We should calculate these exactly when x is an integer # and when doing so is faster. def mpf_harmonic(x, prec, rnd): if x in (fzero, fnan, finf): return x a = mpf_psi0(mpf_add(fone, x, prec+5), prec) return mpf_add(a, mpf_euler(prec+5, rnd), prec, rnd) def mpc_harmonic(z, prec, rnd): if z[1] == fzero: return (mpf_harmonic(z[0], prec, rnd), fzero) a = mpc_psi0(mpc_add_mpf(z, fone, prec+5), prec) return mpc_add_mpf(a, mpf_euler(prec+5, rnd), prec, rnd) def mpf_psi0(x, prec, rnd=round_fast): """ Computation of the digamma function (psi function of order 0) of a real argument. """ sign, man, exp, bc = x wp = prec + 10 if not man: if x == finf: return x if x == fninf or x == fnan: return fnan if x == fzero or (exp >= 0 and sign): raise ValueError("polygamma pole") # Reflection formula if sign and exp+bc > 3: c, s = mpf_cos_sin_pi(x, wp) q = mpf_mul(mpf_div(c, s, wp), mpf_pi(wp), wp) p = mpf_psi0(mpf_sub(fone, x, wp), wp) return mpf_sub(p, q, prec, rnd) # The logarithmic term is accurate enough if (not sign) and bc + exp > wp: return mpf_log(mpf_sub(x, fone, wp), prec, rnd) # Initial recurrence to obtain a large enough x m = to_int(x) n = int(0.11*wp) + 2 s = MPZ_ZERO x = to_fixed(x, wp) one = MPZ_ONE << wp if m < n: for k in xrange(m, n): s -= (one << wp) // x x += one x -= one # Logarithmic term s += to_fixed(mpf_log(from_man_exp(x, -wp, wp), wp), wp) # Endpoint term in Euler-Maclaurin expansion s += (one << wp) // (2*x) # Euler-Maclaurin remainder sum x2 = (x*x) >> wp t = one prev = 0 k = 1 while 1: t = (t*x2) >> wp bsign, bman, bexp, bbc = mpf_bernoulli(2*k, wp) offset = (bexp + 2*wp) if offset >= 0: term = (bman << offset) // (t*(2*k)) else: term = (bman >> (-offset)) // (t*(2*k)) if k & 1: s -= term else: s += term if k > 2 and term >= prev: break prev = term k += 1 return from_man_exp(s, -wp, wp, rnd) def mpc_psi0(z, prec, rnd=round_fast): """ Computation of the digamma function (psi function of order 0) of a complex argument. """ re, im = z # Fall back to the real case if im == fzero: return (mpf_psi0(re, prec, rnd), fzero) wp = prec + 20 sign, man, exp, bc = re # Reflection formula if sign and exp+bc > 3: c = mpc_cos_pi(z, wp) s = mpc_sin_pi(z, wp) q = mpc_mul_mpf(mpc_div(c, s, wp), mpf_pi(wp), wp) p = mpc_psi0(mpc_sub(mpc_one, z, wp), wp) return mpc_sub(p, q, prec, rnd) # Just the logarithmic term if (not sign) and bc + exp > wp: return mpc_log(mpc_sub(z, mpc_one, wp), prec, rnd) # Initial recurrence to obtain a large enough z w = to_int(re) n = int(0.11*wp) + 2 s = mpc_zero if w < n: for k in xrange(w, n): s = mpc_sub(s, mpc_reciprocal(z, wp), wp) z = mpc_add_mpf(z, fone, wp) z = mpc_sub(z, mpc_one, wp) # Logarithmic and endpoint term s = mpc_add(s, mpc_log(z, wp), wp) s = mpc_add(s, mpc_div(mpc_half, z, wp), wp) # Euler-Maclaurin remainder sum z2 = mpc_square(z, wp) t = mpc_one prev = mpc_zero k = 1 eps = mpf_shift(fone, -wp+2) while 1: t = mpc_mul(t, z2, wp) bern = mpf_bernoulli(2*k, wp) term = mpc_mpf_div(bern, mpc_mul_int(t, 2*k, wp), wp) s = mpc_sub(s, term, wp) szterm = mpc_abs(term, 10) if k > 2 and mpf_le(szterm, eps): break prev = term k += 1 return s # Currently unoptimized def mpf_psi(m, x, prec, rnd=round_fast): """ Computation of the polygamma function of arbitrary integer order m >= 0, for a real argument x. """ if m == 0: return mpf_psi0(x, prec, rnd=round_fast) return mpc_psi(m, (x, fzero), prec, rnd)[0] def mpc_psi(m, z, prec, rnd=round_fast): """ Computation of the polygamma function of arbitrary integer order m >= 0, for a complex argument z. """ if m == 0: return mpc_psi0(z, prec, rnd) re, im = z wp = prec + 20 sign, man, exp, bc = re if not im[1]: if im in (finf, fninf, fnan): return (fnan, fnan) if not man: if re == finf and im == fzero: return (fzero, fzero) if re == fnan: return (fnan, fnan) # Recurrence w = to_int(re) n = int(0.4*wp + 4*m) s = mpc_zero if w < n: for k in xrange(w, n): t = mpc_pow_int(z, -m-1, wp) s = mpc_add(s, t, wp) z = mpc_add_mpf(z, fone, wp) zm = mpc_pow_int(z, -m, wp) z2 = mpc_pow_int(z, -2, wp) # 1/m*(z+N)^m integral_term = mpc_div_mpf(zm, from_int(m), wp) s = mpc_add(s, integral_term, wp) # 1/2*(z+N)^(-(m+1)) s = mpc_add(s, mpc_mul_mpf(mpc_div(zm, z, wp), fhalf, wp), wp) a = m + 1 b = 2 k = 1 # Important: we want to sum up to the *relative* error, # not the absolute error, because psi^(m)(z) might be tiny magn = mpc_abs(s, 10) magn = magn[2]+magn[3] eps = mpf_shift(fone, magn-wp+2) while 1: zm = mpc_mul(zm, z2, wp) bern = mpf_bernoulli(2*k, wp) scal = mpf_mul_int(bern, a, wp) scal = mpf_div(scal, from_int(b), wp) term = mpc_mul_mpf(zm, scal, wp) s = mpc_add(s, term, wp) szterm = mpc_abs(term, 10) if k > 2 and mpf_le(szterm, eps): break #print k, to_str(szterm, 10), to_str(eps, 10) a *= (m+2*k)*(m+2*k+1) b *= (2*k+1)*(2*k+2) k += 1 # Scale and sign factor v = mpc_mul_mpf(s, mpf_gamma(from_int(m+1), wp), prec, rnd) if not (m & 1): v = mpf_neg(v[0]), mpf_neg(v[1]) return v #-----------------------------------------------------------------------# # # # Riemann zeta function # # # #-----------------------------------------------------------------------# """ We use zeta(s) = eta(s) / (1 - 2**(1-s)) and Borwein's approximation n-1 ___ k -1 \ (-1) (d_k - d_n) eta(s) ~= ---- ) ------------------ d_n /___ s k = 0 (k + 1) where k ___ i \ (n + i - 1)! 4 d_k = n ) ---------------. /___ (n - i)! (2i)! i = 0 If s = a + b*I, the absolute error for eta(s) is bounded by 3 (1 + 2|b|) ------------ * exp(|b| pi/2) n (3+sqrt(8)) Disregarding the linear term, we have approximately, log(err) ~= log(exp(1.58*|b|)) - log(5.8**n) log(err) ~= 1.58*|b| - log(5.8)*n log(err) ~= 1.58*|b| - 1.76*n log2(err) ~= 2.28*|b| - 2.54*n So for p bits, we should choose n > (p + 2.28*|b|) / 2.54. References: ----------- Peter Borwein, "An Efficient Algorithm for the Riemann Zeta Function" http://www.cecm.sfu.ca/personal/pborwein/PAPERS/P117.ps http://en.wikipedia.org/wiki/Dirichlet_eta_function """ borwein_cache = {} def borwein_coefficients(n): if n in borwein_cache: return borwein_cache[n] ds = [MPZ_ZERO] * (n+1) d = MPZ_ONE s = ds[0] = MPZ_ONE for i in range(1, n+1): d = d * 4 * (n+i-1) * (n-i+1) d //= ((2*i) * ((2*i)-1)) s += d ds[i] = s borwein_cache[n] = ds return ds ZETA_INT_CACHE_MAX_PREC = 1000 zeta_int_cache = {} def mpf_zeta_int(s, prec, rnd=round_fast): """ Optimized computation of zeta(s) for an integer s. """ wp = prec + 20 s = int(s) if s in zeta_int_cache and zeta_int_cache[s][0] >= wp: return mpf_pos(zeta_int_cache[s][1], prec, rnd) if s < 2: if s == 1: raise ValueError("zeta(1) pole") if not s: return mpf_neg(fhalf) return mpf_div(mpf_bernoulli(-s+1, wp), from_int(s-1), prec, rnd) # 2^-s term vanishes? if s >= wp: return mpf_perturb(fone, 0, prec, rnd) # 5^-s term vanishes? elif s >= wp*0.431: t = one = 1 << wp t += 1 << (wp - s) t += one // (MPZ_THREE ** s) t += 1 << max(0, wp - s*2) return from_man_exp(t, -wp, prec, rnd) else: # Fast enough to sum directly? # Even better, we use the Euler product (idea stolen from pari) m = (float(wp)/(s-1) + 1) if m < 30: needed_terms = int(2.0**m + 1) if needed_terms < int(wp/2.54 + 5) / 10: t = fone for k in list_primes(needed_terms): #print k, needed_terms powprec = int(wp - s*math.log(k,2)) if powprec < 2: break a = mpf_sub(fone, mpf_pow_int(from_int(k), -s, powprec), wp) t = mpf_mul(t, a, wp) return mpf_div(fone, t, wp) # Use Borwein's algorithm n = int(wp/2.54 + 5) d = borwein_coefficients(n) t = MPZ_ZERO s = MPZ(s) for k in xrange(n): t += (((-1)**k * (d[k] - d[n])) << wp) // (k+1)**s t = (t << wp) // (-d[n]) t = (t << wp) // ((1 << wp) - (1 << (wp+1-s))) if (s in zeta_int_cache and zeta_int_cache[s][0] < wp) or (s not in zeta_int_cache): zeta_int_cache[s] = (wp, from_man_exp(t, -wp-wp)) return from_man_exp(t, -wp-wp, prec, rnd) def mpf_zeta(s, prec, rnd=round_fast, alt=0): sign, man, exp, bc = s if not man: if s == fzero: if alt: return fhalf else: return mpf_neg(fhalf) if s == finf: return fone return fnan wp = prec + 20 # First term vanishes? if (not sign) and (exp + bc > (math.log(wp,2) + 2)): return mpf_perturb(fone, alt, prec, rnd) # Optimize for integer arguments elif exp >= 0: if alt: if s == fone: return mpf_ln2(prec, rnd) z = mpf_zeta_int(to_int(s), wp, negative_rnd[rnd]) q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp) return mpf_mul(z, q, prec, rnd) else: return mpf_zeta_int(to_int(s), prec, rnd) # Negative: use the reflection formula # Borwein only proves the accuracy bound for x >= 1/2. However, based on # tests, the accuracy without reflection is quite good even some distance # to the left of 1/2. XXX: verify this. if sign: # XXX: could use the separate refl. formula for Dirichlet eta if alt: q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp) return mpf_mul(mpf_zeta(s, wp), q, prec, rnd) # XXX: -1 should be done exactly y = mpf_sub(fone, s, 10*wp) a = mpf_gamma(y, wp) b = mpf_zeta(y, wp) c = mpf_sin_pi(mpf_shift(s, -1), wp) wp2 = wp + max(0,exp+bc) pi = mpf_pi(wp+wp2) d = mpf_div(mpf_pow(mpf_shift(pi, 1), s, wp2), pi, wp2) return mpf_mul(a,mpf_mul(b,mpf_mul(c,d,wp),wp),prec,rnd) # Near pole r = mpf_sub(fone, s, wp) asign, aman, aexp, abc = mpf_abs(r) pole_dist = -2*(aexp+abc) if pole_dist > wp: if alt: return mpf_ln2(prec, rnd) else: q = mpf_neg(mpf_div(fone, r, wp)) return mpf_add(q, mpf_euler(wp), prec, rnd) else: wp += max(0, pole_dist) t = MPZ_ZERO #wp += 16 - (prec & 15) # Use Borwein's algorithm n = int(wp/2.54 + 5) d = borwein_coefficients(n) t = MPZ_ZERO sf = to_fixed(s, wp) ln2 = ln2_fixed(wp) for k in xrange(n): u = (-sf*log_int_fixed(k+1, wp, ln2)) >> wp #esign, eman, eexp, ebc = mpf_exp(u, wp) #offset = eexp + wp #if offset >= 0: # w = ((d[k] - d[n]) * eman) << offset #else: # w = ((d[k] - d[n]) * eman) >> (-offset) eman = exp_fixed(u, wp, ln2) w = (d[k] - d[n]) * eman if k & 1: t -= w else: t += w t = t // (-d[n]) t = from_man_exp(t, -wp, wp) if alt: return mpf_pos(t, prec, rnd) else: q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp) return mpf_div(t, q, prec, rnd) def mpc_zeta(s, prec, rnd=round_fast, alt=0, force=False): re, im = s if im == fzero: return mpf_zeta(re, prec, rnd, alt), fzero # slow for large s if (not force) and mpf_gt(mpc_abs(s, 10), from_int(prec)): raise NotImplementedError wp = prec + 20 # Near pole r = mpc_sub(mpc_one, s, wp) asign, aman, aexp, abc = mpc_abs(r, 10) pole_dist = -2*(aexp+abc) if pole_dist > wp: if alt: q = mpf_ln2(wp) y = mpf_mul(q, mpf_euler(wp), wp) g = mpf_shift(mpf_mul(q, q, wp), -1) g = mpf_sub(y, g) z = mpc_mul_mpf(r, mpf_neg(g), wp) z = mpc_add_mpf(z, q, wp) return mpc_pos(z, prec, rnd) else: q = mpc_neg(mpc_div(mpc_one, r, wp)) q = mpc_add_mpf(q, mpf_euler(wp), wp) return mpc_pos(q, prec, rnd) else: wp += max(0, pole_dist) # Reflection formula. To be rigorous, we should reflect to the left of # re = 1/2 (see comments for mpf_zeta), but this leads to unnecessary # slowdown for interesting values of s if mpf_lt(re, fzero): # XXX: could use the separate refl. formula for Dirichlet eta if alt: q = mpc_sub(mpc_one, mpc_pow(mpc_two, mpc_sub(mpc_one, s, wp), wp), wp) return mpc_mul(mpc_zeta(s, wp), q, prec, rnd) # XXX: -1 should be done exactly y = mpc_sub(mpc_one, s, 10*wp) a = mpc_gamma(y, wp) b = mpc_zeta(y, wp) c = mpc_sin_pi(mpc_shift(s, -1), wp) rsign, rman, rexp, rbc = re isign, iman, iexp, ibc = im mag = max(rexp+rbc, iexp+ibc) wp2 = wp + max(0, mag) pi = mpf_pi(wp+wp2) pi2 = (mpf_shift(pi, 1), fzero) d = mpc_div_mpf(mpc_pow(pi2, s, wp2), pi, wp2) return mpc_mul(a,mpc_mul(b,mpc_mul(c,d,wp),wp),prec,rnd) n = int(wp/2.54 + 5) n += int(0.9*abs(to_int(im))) d = borwein_coefficients(n) ref = to_fixed(re, wp) imf = to_fixed(im, wp) tre = MPZ_ZERO tim = MPZ_ZERO one = MPZ_ONE << wp one_2wp = MPZ_ONE << (2*wp) critical_line = re == fhalf ln2 = ln2_fixed(wp) pi2 = pi_fixed(wp-1) wp2 = wp+wp for k in xrange(n): log = log_int_fixed(k+1, wp, ln2) # A square root is much cheaper than an exp if critical_line: w = one_2wp // isqrt_fast((k+1) << wp2) else: w = exp_fixed((-ref*log) >> wp, wp) if k & 1: w *= (d[n] - d[k]) else: w *= (d[k] - d[n]) wre, wim = cos_sin_fixed((-imf*log)>>wp, wp, pi2) tre += (w * wre) >> wp tim += (w * wim) >> wp tre //= (-d[n]) tim //= (-d[n]) tre = from_man_exp(tre, -wp, wp) tim = from_man_exp(tim, -wp, wp) if alt: return mpc_pos((tre, tim), prec, rnd) else: q = mpc_sub(mpc_one, mpc_pow(mpc_two, r, wp), wp) return mpc_div((tre, tim), q, prec, rnd) def mpf_altzeta(s, prec, rnd=round_fast): return mpf_zeta(s, prec, rnd, 1) def mpc_altzeta(s, prec, rnd=round_fast): return mpc_zeta(s, prec, rnd, 1) # Not optimized currently mpf_zetasum = None def pow_fixed(x, n, wp): if n == 1: return x y = MPZ_ONE << wp while n: if n & 1: y = (y*x) >> wp n -= 1 x = (x*x) >> wp n //= 2 return y # TODO: optimize / cleanup interface / unify with list_primes sieve_cache = [] primes_cache = [] mult_cache = [] def primesieve(n): global sieve_cache, primes_cache, mult_cache if n < len(sieve_cache): sieve = sieve_cache#[:n+1] primes = primes_cache[:primes_cache.index(max(sieve))+1] mult = mult_cache#[:n+1] return sieve, primes, mult sieve = [0] * (n+1) mult = [0] * (n+1) primes = list_primes(n) for p in primes: #sieve[p::p] = p for k in xrange(p,n+1,p): sieve[k] = p for i, p in enumerate(sieve): if i >= 2: m = 1 n = i // p while not n % p: n //= p m += 1 mult[i] = m sieve_cache = sieve primes_cache = primes mult_cache = mult return sieve, primes, mult def zetasum_sieved(critical_line, sre, sim, a, n, wp): if a < 1: raise ValueError("a cannot be less than 1") sieve, primes, mult = primesieve(a+n) basic_powers = {} one = MPZ_ONE << wp one_2wp = MPZ_ONE << (2*wp) wp2 = wp+wp ln2 = ln2_fixed(wp) pi2 = pi_fixed(wp-1) for p in primes: if p*2 > a+n: break log = log_int_fixed(p, wp, ln2) cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2) if critical_line: u = one_2wp // isqrt_fast(p<<wp2) else: u = exp_fixed((-sre*log)>>wp, wp) pre = (u*cos) >> wp pim = (u*sin) >> wp basic_powers[p] = [(pre, pim)] tre, tim = pre, pim for m in range(1,int(math.log(a+n,p)+0.01)+1): tre, tim = ((pre*tre-pim*tim)>>wp), ((pim*tre+pre*tim)>>wp) basic_powers[p].append((tre,tim)) xre = MPZ_ZERO xim = MPZ_ZERO if a == 1: xre += one aa = max(a,2) for k in xrange(aa, a+n+1): p = sieve[k] if p in basic_powers: m = mult[k] tre, tim = basic_powers[p][m-1] while 1: k //= p**m if k == 1: break p = sieve[k] m = mult[k] pre, pim = basic_powers[p][m-1] tre, tim = ((pre*tre-pim*tim)>>wp), ((pim*tre+pre*tim)>>wp) else: log = log_int_fixed(k, wp, ln2) cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2) if critical_line: u = one_2wp // isqrt_fast(k<<wp2) else: u = exp_fixed((-sre*log)>>wp, wp) tre = (u*cos) >> wp tim = (u*sin) >> wp xre += tre xim += tim return xre, xim # Set to something large to disable ZETASUM_SIEVE_CUTOFF = 10 def mpc_zetasum(s, a, n, derivatives, reflect, prec): """ Fast version of mp._zetasum, assuming s = complex, a = integer. """ wp = prec + 10 derivatives = list(derivatives) have_derivatives = derivatives != [0] have_one_derivative = len(derivatives) == 1 # parse s sre, sim = s critical_line = (sre == fhalf) sre = to_fixed(sre, wp) sim = to_fixed(sim, wp) if a > 0 and n > ZETASUM_SIEVE_CUTOFF and not have_derivatives \ and not reflect and (n < 4e7 or sys.maxsize > 2**32): re, im = zetasum_sieved(critical_line, sre, sim, a, n, wp) xs = [(from_man_exp(re, -wp, prec, 'n'), from_man_exp(im, -wp, prec, 'n'))] return xs, [] maxd = max(derivatives) if not have_one_derivative: derivatives = range(maxd+1) # x_d = 0, y_d = 0 xre = [MPZ_ZERO for d in derivatives] xim = [MPZ_ZERO for d in derivatives] if reflect: yre = [MPZ_ZERO for d in derivatives] yim = [MPZ_ZERO for d in derivatives] else: yre = yim = [] one = MPZ_ONE << wp one_2wp = MPZ_ONE << (2*wp) ln2 = ln2_fixed(wp) pi2 = pi_fixed(wp-1) wp2 = wp+wp for w in xrange(a, a+n+1): log = log_int_fixed(w, wp, ln2) cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2) if critical_line: u = one_2wp // isqrt_fast(w<<wp2) else: u = exp_fixed((-sre*log)>>wp, wp) xterm_re = (u * cos) >> wp xterm_im = (u * sin) >> wp if reflect: reciprocal = (one_2wp // (u*w)) yterm_re = (reciprocal * cos) >> wp yterm_im = (reciprocal * sin) >> wp if have_derivatives: if have_one_derivative: log = pow_fixed(log, maxd, wp) xre[0] += (xterm_re * log) >> wp xim[0] += (xterm_im * log) >> wp if reflect: yre[0] += (yterm_re * log) >> wp yim[0] += (yterm_im * log) >> wp else: t = MPZ_ONE << wp for d in derivatives: xre[d] += (xterm_re * t) >> wp xim[d] += (xterm_im * t) >> wp if reflect: yre[d] += (yterm_re * t) >> wp yim[d] += (yterm_im * t) >> wp t = (t * log) >> wp else: xre[0] += xterm_re xim[0] += xterm_im if reflect: yre[0] += yterm_re yim[0] += yterm_im if have_derivatives: if have_one_derivative: if maxd % 2: xre[0] = -xre[0] xim[0] = -xim[0] if reflect: yre[0] = -yre[0] yim[0] = -yim[0] else: xre = [(-1)**d * xre[d] for d in derivatives] xim = [(-1)**d * xim[d] for d in derivatives] if reflect: yre = [(-1)**d * yre[d] for d in derivatives] yim = [(-1)**d * yim[d] for d in derivatives] xs = [(from_man_exp(xa, -wp, prec, 'n'), from_man_exp(xb, -wp, prec, 'n')) for (xa, xb) in zip(xre, xim)] ys = [(from_man_exp(ya, -wp, prec, 'n'), from_man_exp(yb, -wp, prec, 'n')) for (ya, yb) in zip(yre, yim)] return xs, ys #-----------------------------------------------------------------------# # # # The gamma function (NEW IMPLEMENTATION) # # # #-----------------------------------------------------------------------# # Higher means faster, but more precomputation time MAX_GAMMA_TAYLOR_PREC = 5000 # Need to derive higher bounds for Taylor series to go higher assert MAX_GAMMA_TAYLOR_PREC < 15000 # Use Stirling's series if abs(x) > beta*prec # Important: must be large enough for convergence! GAMMA_STIRLING_BETA = 0.2 SMALL_FACTORIAL_CACHE_SIZE = 150 gamma_taylor_cache = {} gamma_stirling_cache = {} small_factorial_cache = [from_int(ifac(n)) for \ n in range(SMALL_FACTORIAL_CACHE_SIZE+1)] def zeta_array(N, prec): """ zeta(n) = A * pi**n / n! + B where A is a rational number (A = Bernoulli number for n even) and B is an infinite sum over powers of exp(2*pi). (B = 0 for n even). TODO: this is currently only used for gamma, but could be very useful elsewhere. """ extra = 30 wp = prec+extra zeta_values = [MPZ_ZERO] * (N+2) pi = pi_fixed(wp) # STEP 1: one = MPZ_ONE << wp zeta_values[0] = -one//2 f_2pi = mpf_shift(mpf_pi(wp),1) exp_2pi_k = exp_2pi = mpf_exp(f_2pi, wp) # Compute exponential series # Store values of 1/(exp(2*pi*k)-1), # exp(2*pi*k)/(exp(2*pi*k)-1)**2, 1/(exp(2*pi*k)-1)**2 # pi*k*exp(2*pi*k)/(exp(2*pi*k)-1)**2 exps3 = [] k = 1 while 1: tp = wp - 9*k if tp < 1: break # 1/(exp(2*pi*k-1) q1 = mpf_div(fone, mpf_sub(exp_2pi_k, fone, tp), tp) # pi*k*exp(2*pi*k)/(exp(2*pi*k)-1)**2 q2 = mpf_mul(exp_2pi_k, mpf_mul(q1,q1,tp), tp) q1 = to_fixed(q1, wp) q2 = to_fixed(q2, wp) q2 = (k * q2 * pi) >> wp exps3.append((q1, q2)) # Multiply for next round exp_2pi_k = mpf_mul(exp_2pi_k, exp_2pi, wp) k += 1 # Exponential sum for n in xrange(3, N+1, 2): s = MPZ_ZERO k = 1 for e1, e2 in exps3: if n%4 == 3: t = e1 // k**n else: U = (n-1)//4 t = (e1 + e2//U) // k**n if not t: break s += t k += 1 zeta_values[n] = -2*s # Even zeta values B = [mpf_abs(mpf_bernoulli(k,wp)) for k in xrange(N+2)] pi_pow = fpi = mpf_pow_int(mpf_shift(mpf_pi(wp), 1), 2, wp) pi_pow = mpf_div(pi_pow, from_int(4), wp) for n in xrange(2,N+2,2): z = mpf_mul(B[n], pi_pow, wp) zeta_values[n] = to_fixed(z, wp) pi_pow = mpf_mul(pi_pow, fpi, wp) pi_pow = mpf_div(pi_pow, from_int((n+1)*(n+2)), wp) # Zeta sum reciprocal_pi = (one << wp) // pi for n in xrange(3, N+1, 4): U = (n-3)//4 s = zeta_values[4*U+4]*(4*U+7)//4 for k in xrange(1, U+1): s -= (zeta_values[4*k] * zeta_values[4*U+4-4*k]) >> wp zeta_values[n] += (2*s*reciprocal_pi) >> wp for n in xrange(5, N+1, 4): U = (n-1)//4 s = zeta_values[4*U+2]*(2*U+1) for k in xrange(1, 2*U+1): s += ((-1)**k*2*k* zeta_values[2*k] * zeta_values[4*U+2-2*k])>>wp zeta_values[n] += ((s*reciprocal_pi)>>wp)//(2*U) return [x>>extra for x in zeta_values] def gamma_taylor_coefficients(inprec): """ Gives the Taylor coefficients of 1/gamma(1+x) as a list of fixed-point numbers. Enough coefficients are returned to ensure that the series converges to the given precision when x is in [0.5, 1.5]. """ # Reuse nearby cache values (small case) if inprec < 400: prec = inprec + (10-(inprec%10)) elif inprec < 1000: prec = inprec + (30-(inprec%30)) else: prec = inprec if prec in gamma_taylor_cache: return gamma_taylor_cache[prec], prec # Experimentally determined bounds if prec < 1000: N = int(prec**0.76 + 2) else: # Valid to at least 15000 bits N = int(prec**0.787 + 2) # Reuse higher precision values for cprec in gamma_taylor_cache: if cprec > prec: coeffs = [x>>(cprec-prec) for x in gamma_taylor_cache[cprec][-N:]] if inprec < 1000: gamma_taylor_cache[prec] = coeffs return coeffs, prec # Cache at a higher precision (large case) if prec > 1000: prec = int(prec * 1.2) wp = prec + 20 A = [0] * N A[0] = MPZ_ZERO A[1] = MPZ_ONE << wp A[2] = euler_fixed(wp) # SLOW, reference implementation #zeta_values = [0,0]+[to_fixed(mpf_zeta_int(k,wp),wp) for k in xrange(2,N)] zeta_values = zeta_array(N, wp) for k in xrange(3, N): a = (-A[2]*A[k-1])>>wp for j in xrange(2,k): a += ((-1)**j * zeta_values[j] * A[k-j]) >> wp a //= (1-k) A[k] = a A = [a>>20 for a in A] A = A[::-1] A = A[:-1] gamma_taylor_cache[prec] = A #return A, prec return gamma_taylor_coefficients(inprec) def gamma_fixed_taylor(xmpf, x, wp, prec, rnd, type): # Determine nearest multiple of N/2 #n = int(x >> (wp-1)) #steps = (n-1)>>1 nearest_int = ((x >> (wp-1)) + MPZ_ONE) >> 1 one = MPZ_ONE << wp coeffs, cwp = gamma_taylor_coefficients(wp) if nearest_int > 0: r = one for i in xrange(nearest_int-1): x -= one r = (r*x) >> wp x -= one p = MPZ_ZERO for c in coeffs: p = c + ((x*p)>>wp) p >>= (cwp-wp) if type == 0: return from_man_exp((r<<wp)//p, -wp, prec, rnd) if type == 2: return mpf_shift(from_rational(p, (r<<wp), prec, rnd), wp) if type == 3: return mpf_log(mpf_abs(from_man_exp((r<<wp)//p, -wp)), prec, rnd) else: r = one for i in xrange(-nearest_int): r = (r*x) >> wp x += one p = MPZ_ZERO for c in coeffs: p = c + ((x*p)>>wp) p >>= (cwp-wp) if wp - bitcount(abs(x)) > 10: # pass very close to 0, so do floating-point multiply g = mpf_add(xmpf, from_int(-nearest_int)) # exact r = from_man_exp(p*r,-wp-wp) r = mpf_mul(r, g, wp) if type == 0: return mpf_div(fone, r, prec, rnd) if type == 2: return mpf_pos(r, prec, rnd) if type == 3: return mpf_log(mpf_abs(mpf_div(fone, r, wp)), prec, rnd) else: r = from_man_exp(x*p*r,-3*wp) if type == 0: return mpf_div(fone, r, prec, rnd) if type == 2: return mpf_pos(r, prec, rnd) if type == 3: return mpf_neg(mpf_log(mpf_abs(r), prec, rnd)) def stirling_coefficient(n): if n in gamma_stirling_cache: return gamma_stirling_cache[n] p, q = bernfrac(n) q *= MPZ(n*(n-1)) gamma_stirling_cache[n] = p, q, bitcount(abs(p)), bitcount(q) return gamma_stirling_cache[n] def real_stirling_series(x, prec): """ Sums the rational part of Stirling's expansion, log(sqrt(2*pi)) - z + 1/(12*z) - 1/(360*z^3) + ... """ t = (MPZ_ONE<<(prec+prec)) // x # t = 1/x u = (t*t)>>prec # u = 1/x**2 s = ln_sqrt2pi_fixed(prec) - x # Add initial terms of Stirling's series s += t//12; t = (t*u)>>prec s -= t//360; t = (t*u)>>prec s += t//1260; t = (t*u)>>prec s -= t//1680; t = (t*u)>>prec if not t: return s s += t//1188; t = (t*u)>>prec s -= 691*t//360360; t = (t*u)>>prec s += t//156; t = (t*u)>>prec if not t: return s s -= 3617*t//122400; t = (t*u)>>prec s += 43867*t//244188; t = (t*u)>>prec s -= 174611*t//125400; t = (t*u)>>prec if not t: return s k = 22 # From here on, the coefficients are growing, so we # have to keep t at a roughly constant size usize = bitcount(abs(u)) tsize = bitcount(abs(t)) texp = 0 while 1: p, q, pb, qb = stirling_coefficient(k) term_mag = tsize + pb + texp shift = -texp m = pb - term_mag if m > 0 and shift < m: p >>= m shift -= m m = tsize - term_mag if m > 0 and shift < m: w = t >> m shift -= m else: w = t term = (t*p//q) >> shift if not term: break s += term t = (t*u) >> usize texp -= (prec - usize) k += 2 return s def complex_stirling_series(x, y, prec): # t = 1/z _m = (x*x + y*y) >> prec tre = (x << prec) // _m tim = (-y << prec) // _m # u = 1/z**2 ure = (tre*tre - tim*tim) >> prec uim = tim*tre >> (prec-1) # s = log(sqrt(2*pi)) - z sre = ln_sqrt2pi_fixed(prec) - x sim = -y # Add initial terms of Stirling's series sre += tre//12; sim += tim//12; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) sre -= tre//360; sim -= tim//360; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) sre += tre//1260; sim += tim//1260; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) sre -= tre//1680; sim -= tim//1680; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) if abs(tre) + abs(tim) < 5: return sre, sim sre += tre//1188; sim += tim//1188; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) sre -= 691*tre//360360; sim -= 691*tim//360360; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) sre += tre//156; sim += tim//156; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) if abs(tre) + abs(tim) < 5: return sre, sim sre -= 3617*tre//122400; sim -= 3617*tim//122400; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) sre += 43867*tre//244188; sim += 43867*tim//244188; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) sre -= 174611*tre//125400; sim -= 174611*tim//125400; tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec) if abs(tre) + abs(tim) < 5: return sre, sim k = 22 # From here on, the coefficients are growing, so we # have to keep t at a roughly constant size usize = bitcount(max(abs(ure), abs(uim))) tsize = bitcount(max(abs(tre), abs(tim))) texp = 0 while 1: p, q, pb, qb = stirling_coefficient(k) term_mag = tsize + pb + texp shift = -texp m = pb - term_mag if m > 0 and shift < m: p >>= m shift -= m m = tsize - term_mag if m > 0 and shift < m: wre = tre >> m wim = tim >> m shift -= m else: wre = tre wim = tim termre = (tre*p//q) >> shift termim = (tim*p//q) >> shift if abs(termre) + abs(termim) < 5: break sre += termre sim += termim tre, tim = ((tre*ure - tim*uim)>>usize), \ ((tre*uim + tim*ure)>>usize) texp -= (prec - usize) k += 2 return sre, sim def mpf_gamma(x, prec, rnd='d', type=0): """ This function implements multipurpose evaluation of the gamma function, G(x), as well as the following versions of the same: type = 0 -- G(x) [standard gamma function] type = 1 -- G(x+1) = x*G(x+1) = x! [factorial] type = 2 -- 1/G(x) [reciprocal gamma function] type = 3 -- log(|G(x)|) [log-gamma function, real part] """ # Specal values sign, man, exp, bc = x if not man: if x == fzero: if type == 1: return fone if type == 2: return fzero raise ValueError("gamma function pole") if x == finf: if type == 2: return fzero return finf return fnan # First of all, for log gamma, numbers can be well beyond the fixed-point # range, so we must take care of huge numbers before e.g. trying # to convert x to the nearest integer if type == 3: wp = prec+20 if exp+bc > wp and not sign: return mpf_sub(mpf_mul(x, mpf_log(x, wp), wp), x, prec, rnd) # We strongly want to special-case small integers is_integer = exp >= 0 if is_integer: # Poles if sign: if type == 2: return fzero raise ValueError("gamma function pole") # n = x n = man << exp if n < SMALL_FACTORIAL_CACHE_SIZE: if type == 0: return mpf_pos(small_factorial_cache[n-1], prec, rnd) if type == 1: return mpf_pos(small_factorial_cache[n], prec, rnd) if type == 2: return mpf_div(fone, small_factorial_cache[n-1], prec, rnd) if type == 3: return mpf_log(small_factorial_cache[n-1], prec, rnd) else: # floor(abs(x)) n = int(man >> (-exp)) # Estimate size and precision # Estimate log(gamma(|x|),2) as x*log(x,2) mag = exp + bc gamma_size = n*mag if type == 3: wp = prec + 20 else: wp = prec + bitcount(gamma_size) + 20 # Very close to 0, pole if mag < -wp: if type == 0: return mpf_sub(mpf_div(fone,x, wp),mpf_shift(fone,-wp),prec,rnd) if type == 1: return mpf_sub(fone, x, prec, rnd) if type == 2: return mpf_add(x, mpf_shift(fone,mag-wp), prec, rnd) if type == 3: return mpf_neg(mpf_log(mpf_abs(x), prec, rnd)) # From now on, we assume having a gamma function if type == 1: return mpf_gamma(mpf_add(x, fone), prec, rnd, 0) # Special case integers (those not small enough to be caught above, # but still small enough for an exact factorial to be faster # than an approximate algorithm), and half-integers if exp >= -1: if is_integer: if gamma_size < 10*wp: if type == 0: return from_int(ifac(n-1), prec, rnd) if type == 2: return from_rational(MPZ_ONE, ifac(n-1), prec, rnd) if type == 3: return mpf_log(from_int(ifac(n-1)), prec, rnd) # half-integer if n < 100 or gamma_size < 10*wp: if sign: w = sqrtpi_fixed(wp) if n % 2: f = ifac2(2*n+1) else: f = -ifac2(2*n+1) if type == 0: return mpf_shift(from_rational(w, f, prec, rnd), -wp+n+1) if type == 2: return mpf_shift(from_rational(f, w, prec, rnd), wp-n-1) if type == 3: return mpf_log(mpf_shift(from_rational(w, abs(f), prec, rnd), -wp+n+1), prec, rnd) elif n == 0: if type == 0: return mpf_sqrtpi(prec, rnd) if type == 2: return mpf_div(fone, mpf_sqrtpi(wp), prec, rnd) if type == 3: return mpf_log(mpf_sqrtpi(wp), prec, rnd) else: w = sqrtpi_fixed(wp) w = from_man_exp(w * ifac2(2*n-1), -wp-n) if type == 0: return mpf_pos(w, prec, rnd) if type == 2: return mpf_div(fone, w, prec, rnd) if type == 3: return mpf_log(mpf_abs(w), prec, rnd) # Convert to fixed point offset = exp + wp if offset >= 0: absxman = man << offset else: absxman = man >> (-offset) # For log gamma, provide accurate evaluation for x = 1+eps and 2+eps if type == 3 and not sign: one = MPZ_ONE << wp one_dist = abs(absxman-one) two_dist = abs(absxman-2*one) cancellation = (wp - bitcount(min(one_dist, two_dist))) if cancellation > 10: xsub1 = mpf_sub(fone, x) xsub2 = mpf_sub(ftwo, x) xsub1mag = xsub1[2]+xsub1[3] xsub2mag = xsub2[2]+xsub2[3] if xsub1mag < -wp: return mpf_mul(mpf_euler(wp), mpf_sub(fone, x), prec, rnd) if xsub2mag < -wp: return mpf_mul(mpf_sub(fone, mpf_euler(wp)), mpf_sub(x, ftwo), prec, rnd) # Proceed but increase precision wp += max(-xsub1mag, -xsub2mag) offset = exp + wp if offset >= 0: absxman = man << offset else: absxman = man >> (-offset) # Use Taylor series if appropriate n_for_stirling = int(GAMMA_STIRLING_BETA*wp) if n < max(100, n_for_stirling) and wp < MAX_GAMMA_TAYLOR_PREC: if sign: absxman = -absxman return gamma_fixed_taylor(x, absxman, wp, prec, rnd, type) # Use Stirling's series # First ensure that |x| is large enough for rapid convergence xorig = x # Argument reduction r = 0 if n < n_for_stirling: r = one = MPZ_ONE << wp d = n_for_stirling - n for k in xrange(d): r = (r * absxman) >> wp absxman += one x = xabs = from_man_exp(absxman, -wp) if sign: x = mpf_neg(x) else: xabs = mpf_abs(x) # Asymptotic series y = real_stirling_series(absxman, wp) u = to_fixed(mpf_log(xabs, wp), wp) u = ((absxman - (MPZ_ONE<<(wp-1))) * u) >> wp y += u w = from_man_exp(y, -wp) # Compute final value if sign: # Reflection formula A = mpf_mul(mpf_sin_pi(xorig, wp), xorig, wp) B = mpf_neg(mpf_pi(wp)) if type == 0 or type == 2: A = mpf_mul(A, mpf_exp(w, wp)) if r: B = mpf_mul(B, from_man_exp(r, -wp), wp) if type == 0: return mpf_div(B, A, prec, rnd) if type == 2: return mpf_div(A, B, prec, rnd) if type == 3: if r: B = mpf_mul(B, from_man_exp(r, -wp), wp) A = mpf_add(mpf_log(mpf_abs(A), wp), w, wp) return mpf_sub(mpf_log(mpf_abs(B), wp), A, prec, rnd) else: if type == 0: if r: return mpf_div(mpf_exp(w, wp), from_man_exp(r, -wp), prec, rnd) return mpf_exp(w, prec, rnd) if type == 2: if r: return mpf_div(from_man_exp(r, -wp), mpf_exp(w, wp), prec, rnd) return mpf_exp(mpf_neg(w), prec, rnd) if type == 3: if r: return mpf_sub(w, mpf_log(from_man_exp(r,-wp), wp), prec, rnd) return mpf_pos(w, prec, rnd) def mpc_gamma(z, prec, rnd='d', type=0): a, b = z asign, aman, aexp, abc = a bsign, bman, bexp, bbc = b if b == fzero: # Imaginary part on negative half-axis for log-gamma function if type == 3 and asign: re = mpf_gamma(a, prec, rnd, 3) n = (-aman) >> (-aexp) im = mpf_mul_int(mpf_pi(prec+10), n, prec, rnd) return re, im return mpf_gamma(a, prec, rnd, type), fzero # Some kind of complex inf/nan if (not aman and aexp) or (not bman and bexp): return (fnan, fnan) # Initial working precision wp = prec + 20 amag = aexp+abc bmag = bexp+bbc if aman: mag = max(amag, bmag) else: mag = bmag # Close to 0 if mag < -8: if mag < -wp: # 1/gamma(z) = z + euler*z^2 + O(z^3) v = mpc_add(z, mpc_mul_mpf(mpc_mul(z,z,wp),mpf_euler(wp),wp), wp) if type == 0: return mpc_reciprocal(v, prec, rnd) if type == 1: return mpc_div(z, v, prec, rnd) if type == 2: return mpc_pos(v, prec, rnd) if type == 3: return mpc_log(mpc_reciprocal(v, prec), prec, rnd) elif type != 1: wp += (-mag) # Handle huge log-gamma values; must do this before converting to # a fixed-point value. TODO: determine a precise cutoff of validity # depending on amag and bmag if type == 3 and mag > wp and ((not asign) or (bmag >= amag)): return mpc_sub(mpc_mul(z, mpc_log(z, wp), wp), z, prec, rnd) # From now on, we assume having a gamma function if type == 1: return mpc_gamma((mpf_add(a, fone), b), prec, rnd, 0) an = abs(to_int(a)) bn = abs(to_int(b)) absn = max(an, bn) gamma_size = absn*mag if type == 3: pass else: wp += bitcount(gamma_size) # Reflect to the right half-plane. Note that Stirling's expansion # is valid in the left half-plane too, as long as we're not too close # to the real axis, but in order to use this argument reduction # in the negative direction must be implemented. #need_reflection = asign and ((bmag < 0) or (amag-bmag > 4)) need_reflection = asign zorig = z if need_reflection: z = mpc_neg(z) asign, aman, aexp, abc = a = z[0] bsign, bman, bexp, bbc = b = z[1] # Imaginary part very small compared to real one? yfinal = 0 balance_prec = 0 if bmag < -10: # Check z ~= 1 and z ~= 2 for loggamma if type == 3: zsub1 = mpc_sub_mpf(z, fone) if zsub1[0] == fzero: cancel1 = -bmag else: cancel1 = -max(zsub1[0][2]+zsub1[0][3], bmag) if cancel1 > wp: pi = mpf_pi(wp) x = mpc_mul_mpf(zsub1, pi, wp) x = mpc_mul(x, x, wp) x = mpc_div_mpf(x, from_int(12), wp) y = mpc_mul_mpf(zsub1, mpf_neg(mpf_euler(wp)), wp) yfinal = mpc_add(x, y, wp) if not need_reflection: return mpc_pos(yfinal, prec, rnd) elif cancel1 > 0: wp += cancel1 zsub2 = mpc_sub_mpf(z, ftwo) if zsub2[0] == fzero: cancel2 = -bmag else: cancel2 = -max(zsub2[0][2]+zsub2[0][3], bmag) if cancel2 > wp: pi = mpf_pi(wp) t = mpf_sub(mpf_mul(pi, pi), from_int(6)) x = mpc_mul_mpf(mpc_mul(zsub2, zsub2, wp), t, wp) x = mpc_div_mpf(x, from_int(12), wp) y = mpc_mul_mpf(zsub2, mpf_sub(fone, mpf_euler(wp)), wp) yfinal = mpc_add(x, y, wp) if not need_reflection: return mpc_pos(yfinal, prec, rnd) elif cancel2 > 0: wp += cancel2 if bmag < -wp: # Compute directly from the real gamma function. pp = 2*(wp+10) aabs = mpf_abs(a) eps = mpf_shift(fone, amag-wp) x1 = mpf_gamma(aabs, pp, type=type) x2 = mpf_gamma(mpf_add(aabs, eps), pp, type=type) xprime = mpf_div(mpf_sub(x2, x1, pp), eps, pp) y = mpf_mul(b, xprime, prec, rnd) yfinal = (x1, y) # Note: we still need to use the reflection formula for # near-poles, and the correct branch of the log-gamma function if not need_reflection: return mpc_pos(yfinal, prec, rnd) else: balance_prec += (-bmag) wp += balance_prec n_for_stirling = int(GAMMA_STIRLING_BETA*wp) need_reduction = absn < n_for_stirling afix = to_fixed(a, wp) bfix = to_fixed(b, wp) r = 0 if not yfinal: zprered = z # Argument reduction if absn < n_for_stirling: absn = complex(an, bn) d = int((1 + n_for_stirling**2 - bn**2)**0.5 - an) rre = one = MPZ_ONE << wp rim = MPZ_ZERO for k in xrange(d): rre, rim = ((afix*rre-bfix*rim)>>wp), ((afix*rim + bfix*rre)>>wp) afix += one r = from_man_exp(rre, -wp), from_man_exp(rim, -wp) a = from_man_exp(afix, -wp) z = a, b yre, yim = complex_stirling_series(afix, bfix, wp) # (z-1/2)*log(z) + S lre, lim = mpc_log(z, wp) lre = to_fixed(lre, wp) lim = to_fixed(lim, wp) yre = ((lre*afix - lim*bfix)>>wp) - (lre>>1) + yre yim = ((lre*bfix + lim*afix)>>wp) - (lim>>1) + yim y = from_man_exp(yre, -wp), from_man_exp(yim, -wp) if r and type == 3: # If re(z) > 0 and abs(z) <= 4, the branches of loggamma(z) # and log(gamma(z)) coincide. Otherwise, use the zeroth order # Stirling expansion to compute the correct imaginary part. y = mpc_sub(y, mpc_log(r, wp), wp) zfa = to_float(zprered[0]) zfb = to_float(zprered[1]) zfabs = math.hypot(zfa,zfb) #if not (zfa > 0.0 and zfabs <= 4): yfb = to_float(y[1]) u = math.atan2(zfb, zfa) if zfabs <= 0.5: gi = 0.577216*zfb - u else: gi = -zfb - 0.5*u + zfa*u + zfb*math.log(zfabs) n = int(math.floor((gi-yfb)/(2*math.pi)+0.5)) y = (y[0], mpf_add(y[1], mpf_mul_int(mpf_pi(wp), 2*n, wp), wp)) if need_reflection: if type == 0 or type == 2: A = mpc_mul(mpc_sin_pi(zorig, wp), zorig, wp) B = (mpf_neg(mpf_pi(wp)), fzero) if yfinal: if type == 2: A = mpc_div(A, yfinal, wp) else: A = mpc_mul(A, yfinal, wp) else: A = mpc_mul(A, mpc_exp(y, wp), wp) if r: B = mpc_mul(B, r, wp) if type == 0: return mpc_div(B, A, prec, rnd) if type == 2: return mpc_div(A, B, prec, rnd) # Reflection formula for the log-gamma function with correct branch # http://functions.wolfram.com/GammaBetaErf/LogGamma/16/01/01/0006/ # LogGamma[z] == -LogGamma[-z] - Log[-z] + # Sign[Im[z]] Floor[Re[z]] Pi I + Log[Pi] - # Log[Sin[Pi (z - Floor[Re[z]])]] - # Pi I (1 - Abs[Sign[Im[z]]]) Abs[Floor[Re[z]]] if type == 3: if yfinal: s1 = mpc_neg(yfinal) else: s1 = mpc_neg(y) # s -= log(-z) s1 = mpc_sub(s1, mpc_log(mpc_neg(zorig), wp), wp) # floor(re(z)) rezfloor = mpf_floor(zorig[0]) imzsign = mpf_sign(zorig[1]) pi = mpf_pi(wp) t = mpf_mul(pi, rezfloor) t = mpf_mul_int(t, imzsign, wp) s1 = (s1[0], mpf_add(s1[1], t, wp)) s1 = mpc_add_mpf(s1, mpf_log(pi, wp), wp) t = mpc_sin_pi(mpc_sub_mpf(zorig, rezfloor), wp) t = mpc_log(t, wp) s1 = mpc_sub(s1, t, wp) # Note: may actually be unused, because we fall back # to the mpf_ function for real arguments if not imzsign: t = mpf_mul(pi, mpf_floor(rezfloor), wp) s1 = (s1[0], mpf_sub(s1[1], t, wp)) return mpc_pos(s1, prec, rnd) else: if type == 0: if r: return mpc_div(mpc_exp(y, wp), r, prec, rnd) return mpc_exp(y, prec, rnd) if type == 2: if r: return mpc_div(r, mpc_exp(y, wp), prec, rnd) return mpc_exp(mpc_neg(y), prec, rnd) if type == 3: return mpc_pos(y, prec, rnd) def mpf_factorial(x, prec, rnd='d'): return mpf_gamma(x, prec, rnd, 1) def mpc_factorial(x, prec, rnd='d'): return mpc_gamma(x, prec, rnd, 1) def mpf_rgamma(x, prec, rnd='d'): return mpf_gamma(x, prec, rnd, 2) def mpc_rgamma(x, prec, rnd='d'): return mpc_gamma(x, prec, rnd, 2) def mpf_loggamma(x, prec, rnd='d'): sign, man, exp, bc = x if sign: raise ComplexResult return mpf_gamma(x, prec, rnd, 3) def mpc_loggamma(z, prec, rnd='d'): a, b = z asign, aman, aexp, abc = a bsign, bman, bexp, bbc = b if b == fzero and asign: re = mpf_gamma(a, prec, rnd, 3) n = (-aman) >> (-aexp) im = mpf_mul_int(mpf_pi(prec+10), n, prec, rnd) return re, im return mpc_gamma(z, prec, rnd, 3) def mpf_gamma_int(n, prec, rnd=round_fast): if n < SMALL_FACTORIAL_CACHE_SIZE: return mpf_pos(small_factorial_cache[n-1], prec, rnd) return mpf_gamma(from_int(n), prec, rnd)
78,727
32.009644
88
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/libhyper.py
""" This module implements computation of hypergeometric and related functions. In particular, it provides code for generic summation of hypergeometric series. Optimized versions for various special cases are also provided. """ import operator import math from .backend import MPZ_ZERO, MPZ_ONE, BACKEND, xrange, exec_ from .libintmath import gcd from .libmpf import (\ ComplexResult, round_fast, round_nearest, negative_rnd, bitcount, to_fixed, from_man_exp, from_int, to_int, from_rational, fzero, fone, fnone, ftwo, finf, fninf, fnan, mpf_sign, mpf_add, mpf_abs, mpf_pos, mpf_cmp, mpf_lt, mpf_le, mpf_gt, mpf_min_max, mpf_perturb, mpf_neg, mpf_shift, mpf_sub, mpf_mul, mpf_div, sqrt_fixed, mpf_sqrt, mpf_rdiv_int, mpf_pow_int, to_rational, ) from .libelefun import (\ mpf_pi, mpf_exp, mpf_log, pi_fixed, mpf_cos_sin, mpf_cos, mpf_sin, mpf_sqrt, agm_fixed, ) from .libmpc import (\ mpc_one, mpc_sub, mpc_mul_mpf, mpc_mul, mpc_neg, complex_int_pow, mpc_div, mpc_add_mpf, mpc_sub_mpf, mpc_log, mpc_add, mpc_pos, mpc_shift, mpc_is_infnan, mpc_zero, mpc_sqrt, mpc_abs, mpc_mpf_div, mpc_square, mpc_exp ) from .libintmath import ifac from .gammazeta import mpf_gamma_int, mpf_euler, euler_fixed class NoConvergence(Exception): pass #-----------------------------------------------------------------------# # # # Generic hypergeometric series # # # #-----------------------------------------------------------------------# """ TODO: 1. proper mpq parsing 2. imaginary z special-cased (also: rational, integer?) 3. more clever handling of series that don't converge because of stupid upwards rounding 4. checking for cancellation """ def make_hyp_summator(key): """ Returns a function that sums a generalized hypergeometric series, for given parameter types (integer, rational, real, complex). """ p, q, param_types, ztype = key pstring = "".join(param_types) fname = "hypsum_%i_%i_%s_%s_%s" % (p, q, pstring[:p], pstring[p:], ztype) #print "generating hypsum", fname have_complex_param = 'C' in param_types have_complex_arg = ztype == 'C' have_complex = have_complex_param or have_complex_arg source = [] add = source.append aint = [] arat = [] bint = [] brat = [] areal = [] breal = [] acomplex = [] bcomplex = [] #add("wp = prec + 40") add("MAX = kwargs.get('maxterms', wp*100)") add("HIGH = MPZ_ONE<<epsshift") add("LOW = -HIGH") # Setup code add("SRE = PRE = one = (MPZ_ONE << wp)") if have_complex: add("SIM = PIM = MPZ_ZERO") if have_complex_arg: add("xsign, xm, xe, xbc = z[0]") add("if xsign: xm = -xm") add("ysign, ym, ye, ybc = z[1]") add("if ysign: ym = -ym") else: add("xsign, xm, xe, xbc = z") add("if xsign: xm = -xm") add("offset = xe + wp") add("if offset >= 0:") add(" ZRE = xm << offset") add("else:") add(" ZRE = xm >> (-offset)") if have_complex_arg: add("offset = ye + wp") add("if offset >= 0:") add(" ZIM = ym << offset") add("else:") add(" ZIM = ym >> (-offset)") for i, flag in enumerate(param_types): W = ["A", "B"][i >= p] if flag == 'Z': ([aint,bint][i >= p]).append(i) add("%sINT_%i = coeffs[%i]" % (W, i, i)) elif flag == 'Q': ([arat,brat][i >= p]).append(i) add("%sP_%i, %sQ_%i = coeffs[%i]._mpq_" % (W, i, W, i, i)) elif flag == 'R': ([areal,breal][i >= p]).append(i) add("xsign, xm, xe, xbc = coeffs[%i]._mpf_" % i) add("if xsign: xm = -xm") add("offset = xe + wp") add("if offset >= 0:") add(" %sREAL_%i = xm << offset" % (W, i)) add("else:") add(" %sREAL_%i = xm >> (-offset)" % (W, i)) elif flag == 'C': ([acomplex,bcomplex][i >= p]).append(i) add("__re, __im = coeffs[%i]._mpc_" % i) add("xsign, xm, xe, xbc = __re") add("if xsign: xm = -xm") add("ysign, ym, ye, ybc = __im") add("if ysign: ym = -ym") add("offset = xe + wp") add("if offset >= 0:") add(" %sCRE_%i = xm << offset" % (W, i)) add("else:") add(" %sCRE_%i = xm >> (-offset)" % (W, i)) add("offset = ye + wp") add("if offset >= 0:") add(" %sCIM_%i = ym << offset" % (W, i)) add("else:") add(" %sCIM_%i = ym >> (-offset)" % (W, i)) else: raise ValueError l_areal = len(areal) l_breal = len(breal) cancellable_real = min(l_areal, l_breal) noncancellable_real_num = areal[cancellable_real:] noncancellable_real_den = breal[cancellable_real:] # LOOP add("for n in xrange(1,10**8):") add(" if n in magnitude_check:") add(" p_mag = bitcount(abs(PRE))") if have_complex: add(" p_mag = max(p_mag, bitcount(abs(PIM)))") add(" magnitude_check[n] = wp-p_mag") # Real factors multiplier = " * ".join(["AINT_#".replace("#", str(i)) for i in aint] + \ ["AP_#".replace("#", str(i)) for i in arat] + \ ["BQ_#".replace("#", str(i)) for i in brat]) divisor = " * ".join(["BINT_#".replace("#", str(i)) for i in bint] + \ ["BP_#".replace("#", str(i)) for i in brat] + \ ["AQ_#".replace("#", str(i)) for i in arat] + ["n"]) if multiplier: add(" mul = " + multiplier) add(" div = " + divisor) # Check for singular terms add(" if not div:") if multiplier: add(" if not mul:") add(" break") add(" raise ZeroDivisionError") # Update product if have_complex: # TODO: when there are several real parameters and just a few complex # (maybe just the complex argument), we only need to do about # half as many ops if we accumulate the real factor in a single real variable for k in range(cancellable_real): add(" PRE = PRE * AREAL_%i // BREAL_%i" % (areal[k], breal[k])) for i in noncancellable_real_num: add(" PRE = (PRE * AREAL_#) >> wp".replace("#", str(i))) for i in noncancellable_real_den: add(" PRE = (PRE << wp) // BREAL_#".replace("#", str(i))) for k in range(cancellable_real): add(" PIM = PIM * AREAL_%i // BREAL_%i" % (areal[k], breal[k])) for i in noncancellable_real_num: add(" PIM = (PIM * AREAL_#) >> wp".replace("#", str(i))) for i in noncancellable_real_den: add(" PIM = (PIM << wp) // BREAL_#".replace("#", str(i))) if multiplier: if have_complex_arg: add(" PRE, PIM = (mul*(PRE*ZRE-PIM*ZIM))//div, (mul*(PIM*ZRE+PRE*ZIM))//div") add(" PRE >>= wp") add(" PIM >>= wp") else: add(" PRE = ((mul * PRE * ZRE) >> wp) // div") add(" PIM = ((mul * PIM * ZRE) >> wp) // div") else: if have_complex_arg: add(" PRE, PIM = (PRE*ZRE-PIM*ZIM)//div, (PIM*ZRE+PRE*ZIM)//div") add(" PRE >>= wp") add(" PIM >>= wp") else: add(" PRE = ((PRE * ZRE) >> wp) // div") add(" PIM = ((PIM * ZRE) >> wp) // div") for i in acomplex: add(" PRE, PIM = PRE*ACRE_#-PIM*ACIM_#, PIM*ACRE_#+PRE*ACIM_#".replace("#", str(i))) add(" PRE >>= wp") add(" PIM >>= wp") for i in bcomplex: add(" mag = BCRE_#*BCRE_#+BCIM_#*BCIM_#".replace("#", str(i))) add(" re = PRE*BCRE_# + PIM*BCIM_#".replace("#", str(i))) add(" im = PIM*BCRE_# - PRE*BCIM_#".replace("#", str(i))) add(" PRE = (re << wp) // mag".replace("#", str(i))) add(" PIM = (im << wp) // mag".replace("#", str(i))) else: for k in range(cancellable_real): add(" PRE = PRE * AREAL_%i // BREAL_%i" % (areal[k], breal[k])) for i in noncancellable_real_num: add(" PRE = (PRE * AREAL_#) >> wp".replace("#", str(i))) for i in noncancellable_real_den: add(" PRE = (PRE << wp) // BREAL_#".replace("#", str(i))) if multiplier: add(" PRE = ((PRE * mul * ZRE) >> wp) // div") else: add(" PRE = ((PRE * ZRE) >> wp) // div") # Add product to sum if have_complex: add(" SRE += PRE") add(" SIM += PIM") add(" if (HIGH > PRE > LOW) and (HIGH > PIM > LOW):") add(" break") else: add(" SRE += PRE") add(" if HIGH > PRE > LOW:") add(" break") #add(" from mpmath import nprint, log, ldexp") #add(" nprint([n, log(abs(PRE),2), ldexp(PRE,-wp)])") add(" if n > MAX:") add(" raise NoConvergence('Hypergeometric series converges too slowly. Try increasing maxterms.')") # +1 all parameters for next loop for i in aint: add(" AINT_# += 1".replace("#", str(i))) for i in bint: add(" BINT_# += 1".replace("#", str(i))) for i in arat: add(" AP_# += AQ_#".replace("#", str(i))) for i in brat: add(" BP_# += BQ_#".replace("#", str(i))) for i in areal: add(" AREAL_# += one".replace("#", str(i))) for i in breal: add(" BREAL_# += one".replace("#", str(i))) for i in acomplex: add(" ACRE_# += one".replace("#", str(i))) for i in bcomplex: add(" BCRE_# += one".replace("#", str(i))) if have_complex: add("a = from_man_exp(SRE, -wp, prec, 'n')") add("b = from_man_exp(SIM, -wp, prec, 'n')") add("if SRE:") add(" if SIM:") add(" magn = max(a[2]+a[3], b[2]+b[3])") add(" else:") add(" magn = a[2]+a[3]") add("elif SIM:") add(" magn = b[2]+b[3]") add("else:") add(" magn = -wp+1") add("return (a, b), True, magn") else: add("a = from_man_exp(SRE, -wp, prec, 'n')") add("if SRE:") add(" magn = a[2]+a[3]") add("else:") add(" magn = -wp+1") add("return a, False, magn") source = "\n".join((" " + line) for line in source) source = ("def %s(coeffs, z, prec, wp, epsshift, magnitude_check, **kwargs):\n" % fname) + source namespace = {} exec_(source, globals(), namespace) #print source return source, namespace[fname] if BACKEND == 'sage': def make_hyp_summator(key): """ Returns a function that sums a generalized hypergeometric series, for given parameter types (integer, rational, real, complex). """ from sage.libs.mpmath.ext_main import hypsum_internal p, q, param_types, ztype = key def _hypsum(coeffs, z, prec, wp, epsshift, magnitude_check, **kwargs): return hypsum_internal(p, q, param_types, ztype, coeffs, z, prec, wp, epsshift, magnitude_check, kwargs) return "(none)", _hypsum #-----------------------------------------------------------------------# # # # Error functions # # # #-----------------------------------------------------------------------# # TODO: mpf_erf should call mpf_erfc when appropriate (currently # only the converse delegation is implemented) def mpf_erf(x, prec, rnd=round_fast): sign, man, exp, bc = x if not man: if x == fzero: return fzero if x == finf: return fone if x== fninf: return fnone return fnan size = exp + bc lg = math.log # The approximation erf(x) = 1 is accurate to > x^2 * log(e,2) bits if size > 3 and 2*(size-1) + 0.528766 > lg(prec,2): if sign: return mpf_perturb(fnone, 0, prec, rnd) else: return mpf_perturb(fone, 1, prec, rnd) # erf(x) ~ 2*x/sqrt(pi) close to 0 if size < -prec: # 2*x x = mpf_shift(x,1) c = mpf_sqrt(mpf_pi(prec+20), prec+20) # TODO: interval rounding return mpf_div(x, c, prec, rnd) wp = prec + abs(size) + 25 # Taylor series for erf, fixed-point summation t = abs(to_fixed(x, wp)) t2 = (t*t) >> wp s, term, k = t, 12345, 1 while term: t = ((t * t2) >> wp) // k term = t // (2*k+1) if k & 1: s -= term else: s += term k += 1 s = (s << (wp+1)) // sqrt_fixed(pi_fixed(wp), wp) if sign: s = -s return from_man_exp(s, -wp, prec, rnd) # If possible, we use the asymptotic series for erfc. # This is an alternating divergent asymptotic series, so # the error is at most equal to the first omitted term. # Here we check if the smallest term is small enough # for a given x and precision def erfc_check_series(x, prec): n = to_int(x) if n**2 * 1.44 > prec: return True return False def mpf_erfc(x, prec, rnd=round_fast): sign, man, exp, bc = x if not man: if x == fzero: return fone if x == finf: return fzero if x == fninf: return ftwo return fnan wp = prec + 20 mag = bc+exp # Preserve full accuracy when exponent grows huge wp += max(0, 2*mag) regular_erf = sign or mag < 2 if regular_erf or not erfc_check_series(x, wp): if regular_erf: return mpf_sub(fone, mpf_erf(x, prec+10, negative_rnd[rnd]), prec, rnd) # 1-erf(x) ~ exp(-x^2), increase prec to deal with cancellation n = to_int(x)+1 return mpf_sub(fone, mpf_erf(x, prec + int(n**2*1.44) + 10), prec, rnd) s = term = MPZ_ONE << wp term_prev = 0 t = (2 * to_fixed(x, wp) ** 2) >> wp k = 1 while 1: term = ((term * (2*k - 1)) << wp) // t if k > 4 and term > term_prev or not term: break if k & 1: s -= term else: s += term term_prev = term #print k, to_str(from_man_exp(term, -wp, 50), 10) k += 1 s = (s << wp) // sqrt_fixed(pi_fixed(wp), wp) s = from_man_exp(s, -wp, wp) z = mpf_exp(mpf_neg(mpf_mul(x,x,wp),wp),wp) y = mpf_div(mpf_mul(z, s, wp), x, prec, rnd) return y #-----------------------------------------------------------------------# # # # Exponential integrals # # # #-----------------------------------------------------------------------# def ei_taylor(x, prec): s = t = x k = 2 while t: t = ((t*x) >> prec) // k s += t // k k += 1 return s def complex_ei_taylor(zre, zim, prec): _abs = abs sre = tre = zre sim = tim = zim k = 2 while _abs(tre) + _abs(tim) > 5: tre, tim = ((tre*zre-tim*zim)//k)>>prec, ((tre*zim+tim*zre)//k)>>prec sre += tre // k sim += tim // k k += 1 return sre, sim def ei_asymptotic(x, prec): one = MPZ_ONE << prec x = t = ((one << prec) // x) s = one + x k = 2 while t: t = (k*t*x) >> prec s += t k += 1 return s def complex_ei_asymptotic(zre, zim, prec): _abs = abs one = MPZ_ONE << prec M = (zim*zim + zre*zre) >> prec # 1 / z xre = tre = (zre << prec) // M xim = tim = ((-zim) << prec) // M sre = one + xre sim = xim k = 2 while _abs(tre) + _abs(tim) > 1000: #print tre, tim tre, tim = ((tre*xre-tim*xim)*k)>>prec, ((tre*xim+tim*xre)*k)>>prec sre += tre sim += tim k += 1 if k > prec: raise NoConvergence return sre, sim def mpf_ei(x, prec, rnd=round_fast, e1=False): if e1: x = mpf_neg(x) sign, man, exp, bc = x if e1 and not sign: if x == fzero: return finf raise ComplexResult("E1(x) for x < 0") if man: xabs = 0, man, exp, bc xmag = exp+bc wp = prec + 20 can_use_asymp = xmag > wp if not can_use_asymp: if exp >= 0: xabsint = man << exp else: xabsint = man >> (-exp) can_use_asymp = xabsint > int(wp*0.693) + 10 if can_use_asymp: if xmag > wp: v = fone else: v = from_man_exp(ei_asymptotic(to_fixed(x, wp), wp), -wp) v = mpf_mul(v, mpf_exp(x, wp), wp) v = mpf_div(v, x, prec, rnd) else: wp += 2*int(to_int(xabs)) u = to_fixed(x, wp) v = ei_taylor(u, wp) + euler_fixed(wp) t1 = from_man_exp(v,-wp) t2 = mpf_log(xabs,wp) v = mpf_add(t1, t2, prec, rnd) else: if x == fzero: v = fninf elif x == finf: v = finf elif x == fninf: v = fzero else: v = fnan if e1: v = mpf_neg(v) return v def mpc_ei(z, prec, rnd=round_fast, e1=False): if e1: z = mpc_neg(z) a, b = z asign, aman, aexp, abc = a bsign, bman, bexp, bbc = b if b == fzero: if e1: x = mpf_neg(mpf_ei(a, prec, rnd)) if not asign: y = mpf_neg(mpf_pi(prec, rnd)) else: y = fzero return x, y else: return mpf_ei(a, prec, rnd), fzero if a != fzero: if not aman or not bman: return (fnan, fnan) wp = prec + 40 amag = aexp+abc bmag = bexp+bbc zmag = max(amag, bmag) can_use_asymp = zmag > wp if not can_use_asymp: zabsint = abs(to_int(a)) + abs(to_int(b)) can_use_asymp = zabsint > int(wp*0.693) + 20 try: if can_use_asymp: if zmag > wp: v = fone, fzero else: zre = to_fixed(a, wp) zim = to_fixed(b, wp) vre, vim = complex_ei_asymptotic(zre, zim, wp) v = from_man_exp(vre, -wp), from_man_exp(vim, -wp) v = mpc_mul(v, mpc_exp(z, wp), wp) v = mpc_div(v, z, wp) if e1: v = mpc_neg(v, prec, rnd) else: x, y = v if bsign: v = mpf_pos(x, prec, rnd), mpf_sub(y, mpf_pi(wp), prec, rnd) else: v = mpf_pos(x, prec, rnd), mpf_add(y, mpf_pi(wp), prec, rnd) return v except NoConvergence: pass #wp += 2*max(0,zmag) wp += 2*int(to_int(mpc_abs(z, 5))) zre = to_fixed(a, wp) zim = to_fixed(b, wp) vre, vim = complex_ei_taylor(zre, zim, wp) vre += euler_fixed(wp) v = from_man_exp(vre,-wp), from_man_exp(vim,-wp) if e1: u = mpc_log(mpc_neg(z),wp) else: u = mpc_log(z,wp) v = mpc_add(v, u, prec, rnd) if e1: v = mpc_neg(v) return v def mpf_e1(x, prec, rnd=round_fast): return mpf_ei(x, prec, rnd, True) def mpc_e1(x, prec, rnd=round_fast): return mpc_ei(x, prec, rnd, True) def mpf_expint(n, x, prec, rnd=round_fast, gamma=False): """ E_n(x), n an integer, x real With gamma=True, computes Gamma(n,x) (upper incomplete gamma function) Returns (real, None) if real, otherwise (real, imag) The imaginary part is an optional branch cut term """ sign, man, exp, bc = x if not man: if gamma: if x == fzero: # Actually gamma function pole if n <= 0: return finf, None return mpf_gamma_int(n, prec, rnd), None if x == finf: return fzero, None # TODO: could return finite imaginary value at -inf return fnan, fnan else: if x == fzero: if n > 1: return from_rational(1, n-1, prec, rnd), None else: return finf, None if x == finf: return fzero, None return fnan, fnan n_orig = n if gamma: n = 1-n wp = prec + 20 xmag = exp + bc # Beware of near-poles if xmag < -10: raise NotImplementedError nmag = bitcount(abs(n)) have_imag = n > 0 and sign negx = mpf_neg(x) # Skip series if direct convergence if n == 0 or 2*nmag - xmag < -wp: if gamma: v = mpf_exp(negx, wp) re = mpf_mul(v, mpf_pow_int(x, n_orig-1, wp), prec, rnd) else: v = mpf_exp(negx, wp) re = mpf_div(v, x, prec, rnd) else: # Finite number of terms, or... can_use_asymptotic_series = -3*wp < n <= 0 # ...large enough? if not can_use_asymptotic_series: xi = abs(to_int(x)) m = min(max(1, xi-n), 2*wp) siz = -n*nmag + (m+n)*bitcount(abs(m+n)) - m*xmag - (144*m//100) tol = -wp-10 can_use_asymptotic_series = siz < tol if can_use_asymptotic_series: r = ((-MPZ_ONE) << (wp+wp)) // to_fixed(x, wp) m = n t = r*m s = MPZ_ONE << wp while m and t: s += t m += 1 t = (m*r*t) >> wp v = mpf_exp(negx, wp) if gamma: # ~ exp(-x) * x^(n-1) * (1 + ...) v = mpf_mul(v, mpf_pow_int(x, n_orig-1, wp), wp) else: # ~ exp(-x)/x * (1 + ...) v = mpf_div(v, x, wp) re = mpf_mul(v, from_man_exp(s, -wp), prec, rnd) elif n == 1: re = mpf_neg(mpf_ei(negx, prec, rnd)) elif n > 0 and n < 3*wp: T1 = mpf_neg(mpf_ei(negx, wp)) if gamma: if n_orig & 1: T1 = mpf_neg(T1) else: T1 = mpf_mul(T1, mpf_pow_int(negx, n-1, wp), wp) r = t = to_fixed(x, wp) facs = [1] * (n-1) for k in range(1,n-1): facs[k] = facs[k-1] * k facs = facs[::-1] s = facs[0] << wp for k in range(1, n-1): if k & 1: s -= facs[k] * t else: s += facs[k] * t t = (t*r) >> wp T2 = from_man_exp(s, -wp, wp) T2 = mpf_mul(T2, mpf_exp(negx, wp)) if gamma: T2 = mpf_mul(T2, mpf_pow_int(x, n_orig, wp), wp) R = mpf_add(T1, T2) re = mpf_div(R, from_int(ifac(n-1)), prec, rnd) else: raise NotImplementedError if have_imag: M = from_int(-ifac(n-1)) if gamma: im = mpf_div(mpf_pi(wp), M, prec, rnd) if n_orig & 1: im = mpf_neg(im) else: im = mpf_div(mpf_mul(mpf_pi(wp), mpf_pow_int(negx, n_orig-1, wp), wp), M, prec, rnd) return re, im else: return re, None def mpf_ci_si_taylor(x, wp, which=0): """ 0 - Ci(x) - (euler+log(x)) 1 - Si(x) """ x = to_fixed(x, wp) x2 = -(x*x) >> wp if which == 0: s, t, k = 0, (MPZ_ONE<<wp), 2 else: s, t, k = x, x, 3 while t: t = (t*x2//(k*(k-1)))>>wp s += t//k k += 2 return from_man_exp(s, -wp) def mpc_ci_si_taylor(re, im, wp, which=0): # The following code is only designed for small arguments, # and not too small arguments (for relative accuracy) if re[1]: mag = re[2]+re[3] elif im[1]: mag = im[2]+im[3] if im[1]: mag = max(mag, im[2]+im[3]) if mag > 2 or mag < -wp: raise NotImplementedError wp += (2-mag) zre = to_fixed(re, wp) zim = to_fixed(im, wp) z2re = (zim*zim-zre*zre)>>wp z2im = (-2*zre*zim)>>wp tre = zre tim = zim one = MPZ_ONE<<wp if which == 0: sre, sim, tre, tim, k = 0, 0, (MPZ_ONE<<wp), 0, 2 else: sre, sim, tre, tim, k = zre, zim, zre, zim, 3 while max(abs(tre), abs(tim)) > 2: f = k*(k-1) tre, tim = ((tre*z2re-tim*z2im)//f)>>wp, ((tre*z2im+tim*z2re)//f)>>wp sre += tre//k sim += tim//k k += 2 return from_man_exp(sre, -wp), from_man_exp(sim, -wp) def mpf_ci_si(x, prec, rnd=round_fast, which=2): """ Calculation of Ci(x), Si(x) for real x. which = 0 -- returns (Ci(x), -) which = 1 -- returns (Si(x), -) which = 2 -- returns (Ci(x), Si(x)) Note: if x < 0, Ci(x) needs an additional imaginary term, pi*i. """ wp = prec + 20 sign, man, exp, bc = x ci, si = None, None if not man: if x == fzero: return (fninf, fzero) if x == fnan: return (x, x) ci = fzero if which != 0: if x == finf: si = mpf_shift(mpf_pi(prec, rnd), -1) if x == fninf: si = mpf_neg(mpf_shift(mpf_pi(prec, negative_rnd[rnd]), -1)) return (ci, si) # For small x: Ci(x) ~ euler + log(x), Si(x) ~ x mag = exp+bc if mag < -wp: if which != 0: si = mpf_perturb(x, 1-sign, prec, rnd) if which != 1: y = mpf_euler(wp) xabs = mpf_abs(x) ci = mpf_add(y, mpf_log(xabs, wp), prec, rnd) return ci, si # For huge x: Ci(x) ~ sin(x)/x, Si(x) ~ pi/2 elif mag > wp: if which != 0: if sign: si = mpf_neg(mpf_pi(prec, negative_rnd[rnd])) else: si = mpf_pi(prec, rnd) si = mpf_shift(si, -1) if which != 1: ci = mpf_div(mpf_sin(x, wp), x, prec, rnd) return ci, si else: wp += abs(mag) # Use an asymptotic series? The smallest value of n!/x^n # occurs for n ~ x, where the magnitude is ~ exp(-x). asymptotic = mag-1 > math.log(wp, 2) # Case 1: convergent series near 0 if not asymptotic: if which != 0: si = mpf_pos(mpf_ci_si_taylor(x, wp, 1), prec, rnd) if which != 1: ci = mpf_ci_si_taylor(x, wp, 0) ci = mpf_add(ci, mpf_euler(wp), wp) ci = mpf_add(ci, mpf_log(mpf_abs(x), wp), prec, rnd) return ci, si x = mpf_abs(x) # Case 2: asymptotic series for x >> 1 xf = to_fixed(x, wp) xr = (MPZ_ONE<<(2*wp)) // xf # 1/x s1 = (MPZ_ONE << wp) s2 = xr t = xr k = 2 while t: t = -t t = (t*xr*k)>>wp k += 1 s1 += t t = (t*xr*k)>>wp k += 1 s2 += t s1 = from_man_exp(s1, -wp) s2 = from_man_exp(s2, -wp) s1 = mpf_div(s1, x, wp) s2 = mpf_div(s2, x, wp) cos, sin = mpf_cos_sin(x, wp) # Ci(x) = sin(x)*s1-cos(x)*s2 # Si(x) = pi/2-cos(x)*s1-sin(x)*s2 if which != 0: si = mpf_add(mpf_mul(cos, s1), mpf_mul(sin, s2), wp) si = mpf_sub(mpf_shift(mpf_pi(wp), -1), si, wp) if sign: si = mpf_neg(si) si = mpf_pos(si, prec, rnd) if which != 1: ci = mpf_sub(mpf_mul(sin, s1), mpf_mul(cos, s2), prec, rnd) return ci, si def mpf_ci(x, prec, rnd=round_fast): if mpf_sign(x) < 0: raise ComplexResult return mpf_ci_si(x, prec, rnd, 0)[0] def mpf_si(x, prec, rnd=round_fast): return mpf_ci_si(x, prec, rnd, 1)[1] def mpc_ci(z, prec, rnd=round_fast): re, im = z if im == fzero: ci = mpf_ci_si(re, prec, rnd, 0)[0] if mpf_sign(re) < 0: return (ci, mpf_pi(prec, rnd)) return (ci, fzero) wp = prec + 20 cre, cim = mpc_ci_si_taylor(re, im, wp, 0) cre = mpf_add(cre, mpf_euler(wp), wp) ci = mpc_add((cre, cim), mpc_log(z, wp), prec, rnd) return ci def mpc_si(z, prec, rnd=round_fast): re, im = z if im == fzero: return (mpf_ci_si(re, prec, rnd, 1)[1], fzero) wp = prec + 20 z = mpc_ci_si_taylor(re, im, wp, 1) return mpc_pos(z, prec, rnd) #-----------------------------------------------------------------------# # # # Bessel functions # # # #-----------------------------------------------------------------------# # A Bessel function of the first kind of integer order, J_n(x), is # given by the power series # oo # ___ k 2 k + n # \ (-1) / x \ # J_n(x) = ) ----------- | - | # /___ k! (k + n)! \ 2 / # k = 0 # Simplifying the quotient between two successive terms gives the # ratio x^2 / (-4*k*(k+n)). Hence, we only need one full-precision # multiplication and one division by a small integer per term. # The complex version is very similar, the only difference being # that the multiplication is actually 4 multiplies. # In the general case, we have # J_v(x) = (x/2)**v / v! * 0F1(v+1, (-1/4)*z**2) # TODO: for extremely large x, we could use an asymptotic # trigonometric approximation. # TODO: recompute at higher precision if the fixed-point mantissa # is very small def mpf_besseljn(n, x, prec, rounding=round_fast): prec += 50 negate = n < 0 and n & 1 mag = x[2]+x[3] n = abs(n) wp = prec + 20 + n*bitcount(n) if mag < 0: wp -= n * mag x = to_fixed(x, wp) x2 = (x**2) >> wp if not n: s = t = MPZ_ONE << wp else: s = t = (x**n // ifac(n)) >> ((n-1)*wp + n) k = 1 while t: t = ((t * x2) // (-4*k*(k+n))) >> wp s += t k += 1 if negate: s = -s return from_man_exp(s, -wp, prec, rounding) def mpc_besseljn(n, z, prec, rounding=round_fast): negate = n < 0 and n & 1 n = abs(n) origprec = prec zre, zim = z mag = max(zre[2]+zre[3], zim[2]+zim[3]) prec += 20 + n*bitcount(n) + abs(mag) if mag < 0: prec -= n * mag zre = to_fixed(zre, prec) zim = to_fixed(zim, prec) z2re = (zre**2 - zim**2) >> prec z2im = (zre*zim) >> (prec-1) if not n: sre = tre = MPZ_ONE << prec sim = tim = MPZ_ZERO else: re, im = complex_int_pow(zre, zim, n) sre = tre = (re // ifac(n)) >> ((n-1)*prec + n) sim = tim = (im // ifac(n)) >> ((n-1)*prec + n) k = 1 while abs(tre) + abs(tim) > 3: p = -4*k*(k+n) tre, tim = tre*z2re - tim*z2im, tim*z2re + tre*z2im tre = (tre // p) >> prec tim = (tim // p) >> prec sre += tre sim += tim k += 1 if negate: sre = -sre sim = -sim re = from_man_exp(sre, -prec, origprec, rounding) im = from_man_exp(sim, -prec, origprec, rounding) return (re, im) def mpf_agm(a, b, prec, rnd=round_fast): """ Computes the arithmetic-geometric mean agm(a,b) for nonnegative mpf values a, b. """ asign, aman, aexp, abc = a bsign, bman, bexp, bbc = b if asign or bsign: raise ComplexResult("agm of a negative number") # Handle inf, nan or zero in either operand if not (aman and bman): if a == fnan or b == fnan: return fnan if a == finf: if b == fzero: return fnan return finf if b == finf: if a == fzero: return fnan return finf # agm(0,x) = agm(x,0) = 0 return fzero wp = prec + 20 amag = aexp+abc bmag = bexp+bbc mag_delta = amag - bmag # Reduce to roughly the same magnitude using floating-point AGM abs_mag_delta = abs(mag_delta) if abs_mag_delta > 10: while abs_mag_delta > 10: a, b = mpf_shift(mpf_add(a,b,wp),-1), \ mpf_sqrt(mpf_mul(a,b,wp),wp) abs_mag_delta //= 2 asign, aman, aexp, abc = a bsign, bman, bexp, bbc = b amag = aexp+abc bmag = bexp+bbc mag_delta = amag - bmag #print to_float(a), to_float(b) # Use agm(a,b) = agm(x*a,x*b)/x to obtain a, b ~= 1 min_mag = min(amag,bmag) max_mag = max(amag,bmag) n = 0 # If too small, we lose precision when going to fixed-point if min_mag < -8: n = -min_mag # If too large, we waste time using fixed-point with large numbers elif max_mag > 20: n = -max_mag if n: a = mpf_shift(a, n) b = mpf_shift(b, n) #print to_float(a), to_float(b) af = to_fixed(a, wp) bf = to_fixed(b, wp) g = agm_fixed(af, bf, wp) return from_man_exp(g, -wp-n, prec, rnd) def mpf_agm1(a, prec, rnd=round_fast): """ Computes the arithmetic-geometric mean agm(1,a) for a nonnegative mpf value a. """ return mpf_agm(fone, a, prec, rnd) def mpc_agm(a, b, prec, rnd=round_fast): """ Complex AGM. TODO: * check that convergence works as intended * optimize * select a nonarbitrary branch """ if mpc_is_infnan(a) or mpc_is_infnan(b): return fnan, fnan if mpc_zero in (a, b): return fzero, fzero if mpc_neg(a) == b: return fzero, fzero wp = prec+20 eps = mpf_shift(fone, -wp+10) while 1: a1 = mpc_shift(mpc_add(a, b, wp), -1) b1 = mpc_sqrt(mpc_mul(a, b, wp), wp) a, b = a1, b1 size = mpf_min_max([mpc_abs(a,10), mpc_abs(b,10)])[1] err = mpc_abs(mpc_sub(a, b, 10), 10) if size == fzero or mpf_lt(err, mpf_mul(eps, size)): return a def mpc_agm1(a, prec, rnd=round_fast): return mpc_agm(mpc_one, a, prec, rnd) def mpf_ellipk(x, prec, rnd=round_fast): if not x[1]: if x == fzero: return mpf_shift(mpf_pi(prec, rnd), -1) if x == fninf: return fzero if x == fnan: return x if x == fone: return finf # TODO: for |x| << 1/2, one could use fall back to # pi/2 * hyp2f1_rat((1,2),(1,2),(1,1), x) wp = prec + 15 # Use K(x) = pi/2/agm(1,a) where a = sqrt(1-x) # The sqrt raises ComplexResult if x > 0 a = mpf_sqrt(mpf_sub(fone, x, wp), wp) v = mpf_agm1(a, wp) r = mpf_div(mpf_pi(wp), v, prec, rnd) return mpf_shift(r, -1) def mpc_ellipk(z, prec, rnd=round_fast): re, im = z if im == fzero: if re == finf: return mpc_zero if mpf_le(re, fone): return mpf_ellipk(re, prec, rnd), fzero wp = prec + 15 a = mpc_sqrt(mpc_sub(mpc_one, z, wp), wp) v = mpc_agm1(a, wp) r = mpc_mpf_div(mpf_pi(wp), v, prec, rnd) return mpc_shift(r, -1) def mpf_ellipe(x, prec, rnd=round_fast): # http://functions.wolfram.com/EllipticIntegrals/ # EllipticK/20/01/0001/ # E = (1-m)*(K'(m)*2*m + K(m)) sign, man, exp, bc = x if not man: if x == fzero: return mpf_shift(mpf_pi(prec, rnd), -1) if x == fninf: return finf if x == fnan: return x if x == finf: raise ComplexResult if x == fone: return fone wp = prec+20 mag = exp+bc if mag < -wp: return mpf_shift(mpf_pi(prec, rnd), -1) # Compute a finite difference for K' p = max(mag, 0) - wp h = mpf_shift(fone, p) K = mpf_ellipk(x, 2*wp) Kh = mpf_ellipk(mpf_sub(x, h), 2*wp) Kdiff = mpf_shift(mpf_sub(K, Kh), -p) t = mpf_sub(fone, x) b = mpf_mul(Kdiff, mpf_shift(x,1), wp) return mpf_mul(t, mpf_add(K, b), prec, rnd) def mpc_ellipe(z, prec, rnd=round_fast): re, im = z if im == fzero: if re == finf: return (fzero, finf) if mpf_le(re, fone): return mpf_ellipe(re, prec, rnd), fzero wp = prec + 15 mag = mpc_abs(z, 1) p = max(mag[2]+mag[3], 0) - wp h = mpf_shift(fone, p) K = mpc_ellipk(z, 2*wp) Kh = mpc_ellipk(mpc_add_mpf(z, h, 2*wp), 2*wp) Kdiff = mpc_shift(mpc_sub(Kh, K, wp), -p) t = mpc_sub(mpc_one, z, wp) b = mpc_mul(Kdiff, mpc_shift(z,1), wp) return mpc_mul(t, mpc_add(K, b, wp), prec, rnd)
36,624
30.820156
110
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/six.py
"""Utilities for writing code that runs on Python 2 and 3""" # Copyright (c) 2010-2012 Benjamin Peterson # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import operator import sys import types __author__ = "Benjamin Peterson <benjamin@python.org>" __version__ = "1.2.0" # True if we are running on Python 3. PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, class_types = type, text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = basestring, integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # This is a bit ugly, but it avoids running this again. delattr(tp, self.name) return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _MovedItems(types.ModuleType): """Lazy loading of moved objects""" _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("reload_module", "__builtin__", "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) del attr moves = sys.modules[__name__ + ".moves"] = _MovedItems("moves") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_code = "__code__" _func_defaults = "__defaults__" _iterkeys = "keys" _itervalues = "values" _iteritems = "items" else: _meth_func = "im_func" _meth_self = "im_self" _func_code = "func_code" _func_defaults = "func_defaults" _iterkeys = "iterkeys" _itervalues = "itervalues" _iteritems = "iteritems" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator if PY3: def get_unbound_function(unbound): return unbound Iterator = object def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) else: def get_unbound_function(unbound): return unbound.im_func class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) def iterkeys(d): """Return an iterator over the keys of a dictionary.""" return iter(getattr(d, _iterkeys)()) def itervalues(d): """Return an iterator over the values of a dictionary.""" return iter(getattr(d, _itervalues)()) def iteritems(d): """Return an iterator over the (key, value) pairs of a dictionary.""" return iter(getattr(d, _iteritems)()) if PY3: def b(s): return s.encode("latin-1") def u(s): return s if sys.version_info[1] <= 1: def int2byte(i): return bytes((i,)) else: # This is about 2x faster than the implementation above on 3.2+ int2byte = operator.methodcaller("to_bytes", 1, "big") import io StringIO = io.StringIO BytesIO = io.BytesIO else: def b(s): return s def u(s): return unicode(s, "unicode_escape") int2byte = chr import StringIO StringIO = BytesIO = StringIO.StringIO _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") if PY3: import builtins exec_ = getattr(builtins, "exec") def reraise(tp, value, tb=None): if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value print_ = getattr(builtins, "print") del builtins else: def exec_(code, globs=None, locs=None): """Execute code in a namespace.""" if globs is None: frame = sys._getframe(1) globs = frame.f_globals if locs is None: locs = frame.f_locals del frame elif locs is None: locs = globs exec("""exec code in globs, locs""") exec_("""def reraise(tp, value, tb=None): raise tp, value, tb """) def print_(*args, **kwargs): """The new-style print function.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) _add_doc(reraise, """Reraise an exception.""") def with_metaclass(meta, base=object): """Create a base class with a metaclass.""" return meta("NewBase", (base,), {})
11,855
29.478149
87
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/libelefun.py
""" This module implements computation of elementary transcendental functions (powers, logarithms, trigonometric and hyperbolic functions, inverse trigonometric and hyperbolic) for real floating-point numbers. For complex and interval implementations of the same functions, see libmpc and libmpi. """ import math from bisect import bisect from .backend import xrange from .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_FIVE, BACKEND from .libmpf import ( round_floor, round_ceiling, round_down, round_up, round_nearest, round_fast, ComplexResult, bitcount, bctable, lshift, rshift, giant_steps, sqrt_fixed, from_int, to_int, from_man_exp, to_fixed, to_float, from_float, from_rational, normalize, fzero, fone, fnone, fhalf, finf, fninf, fnan, mpf_cmp, mpf_sign, mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_div, mpf_shift, mpf_rdiv_int, mpf_pow_int, mpf_sqrt, reciprocal_rnd, negative_rnd, mpf_perturb, isqrt_fast ) from .libintmath import ifib #------------------------------------------------------------------------------- # Tuning parameters #------------------------------------------------------------------------------- # Cutoff for computing exp from cosh+sinh. This reduces the # number of terms by half, but also requires a square root which # is expensive with the pure-Python square root code. if BACKEND == 'python': EXP_COSH_CUTOFF = 600 else: EXP_COSH_CUTOFF = 400 # Cutoff for using more than 2 series EXP_SERIES_U_CUTOFF = 1500 # Also basically determined by sqrt if BACKEND == 'python': COS_SIN_CACHE_PREC = 400 else: COS_SIN_CACHE_PREC = 200 COS_SIN_CACHE_STEP = 8 cos_sin_cache = {} # Number of integer logarithms to cache (for zeta sums) MAX_LOG_INT_CACHE = 2000 log_int_cache = {} LOG_TAYLOR_PREC = 2500 # Use Taylor series with caching up to this prec LOG_TAYLOR_SHIFT = 9 # Cache log values in steps of size 2^-N log_taylor_cache = {} # prec/size ratio of x for fastest convergence in AGM formula LOG_AGM_MAG_PREC_RATIO = 20 ATAN_TAYLOR_PREC = 3000 # Same as for log ATAN_TAYLOR_SHIFT = 7 # steps of size 2^-N atan_taylor_cache = {} # ~= next power of two + 20 cache_prec_steps = [22,22] for k in xrange(1, bitcount(LOG_TAYLOR_PREC)+1): cache_prec_steps += [min(2**k,LOG_TAYLOR_PREC)+20] * 2**(k-1) #----------------------------------------------------------------------------# # # # Elementary mathematical constants # # # #----------------------------------------------------------------------------# def constant_memo(f): """ Decorator for caching computed values of mathematical constants. This decorator should be applied to a function taking a single argument prec as input and returning a fixed-point value with the given precision. """ f.memo_prec = -1 f.memo_val = None def g(prec, **kwargs): memo_prec = f.memo_prec if prec <= memo_prec: return f.memo_val >> (memo_prec-prec) newprec = int(prec*1.05+10) f.memo_val = f(newprec, **kwargs) f.memo_prec = newprec return f.memo_val >> (newprec-prec) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g def def_mpf_constant(fixed): """ Create a function that computes the mpf value for a mathematical constant, given a function that computes the fixed-point value. Assumptions: the constant is positive and has magnitude ~= 1; the fixed-point function rounds to floor. """ def f(prec, rnd=round_fast): wp = prec + 20 v = fixed(wp) if rnd in (round_up, round_ceiling): v += 1 return normalize(0, v, -wp, bitcount(v), prec, rnd) f.__doc__ = fixed.__doc__ return f def bsp_acot(q, a, b, hyperbolic): if b - a == 1: a1 = MPZ(2*a + 3) if hyperbolic or a&1: return MPZ_ONE, a1 * q**2, a1 else: return -MPZ_ONE, a1 * q**2, a1 m = (a+b)//2 p1, q1, r1 = bsp_acot(q, a, m, hyperbolic) p2, q2, r2 = bsp_acot(q, m, b, hyperbolic) return q2*p1 + r1*p2, q1*q2, r1*r2 # the acoth(x) series converges like the geometric series for x^2 # N = ceil(p*log(2)/(2*log(x))) def acot_fixed(a, prec, hyperbolic): """ Compute acot(a) or acoth(a) for an integer a with binary splitting; see http://numbers.computation.free.fr/Constants/Algorithms/splitting.html """ N = int(0.35 * prec/math.log(a) + 20) p, q, r = bsp_acot(a, 0,N, hyperbolic) return ((p+q)<<prec)//(q*a) def machin(coefs, prec, hyperbolic=False): """ Evaluate a Machin-like formula, i.e., a linear combination of acot(n) or acoth(n) for specific integer values of n, using fixed- point arithmetic. The input should be a list [(c, n), ...], giving c*acot[h](n) + ... """ extraprec = 10 s = MPZ_ZERO for a, b in coefs: s += MPZ(a) * acot_fixed(MPZ(b), prec+extraprec, hyperbolic) return (s >> extraprec) # Logarithms of integers are needed for various computations involving # logarithms, powers, radix conversion, etc @constant_memo def ln2_fixed(prec): """ Computes ln(2). This is done with a hyperbolic Machin-type formula, with binary splitting at high precision. """ return machin([(18, 26), (-2, 4801), (8, 8749)], prec, True) @constant_memo def ln10_fixed(prec): """ Computes ln(10). This is done with a hyperbolic Machin-type formula. """ return machin([(46, 31), (34, 49), (20, 161)], prec, True) """ For computation of pi, we use the Chudnovsky series: oo ___ k 1 \ (-1) (6 k)! (A + B k) ----- = ) ----------------------- 12 pi /___ 3 3k+3/2 (3 k)! (k!) C k = 0 where A, B, and C are certain integer constants. This series adds roughly 14 digits per term. Note that C^(3/2) can be extracted so that the series contains only rational terms. This makes binary splitting very efficient. The recurrence formulas for the binary splitting were taken from ftp://ftp.gmplib.org/pub/src/gmp-chudnovsky.c Previously, Machin's formula was used at low precision and the AGM iteration was used at high precision. However, the Chudnovsky series is essentially as fast as the Machin formula at low precision and in practice about 3x faster than the AGM at high precision (despite theoretically having a worse asymptotic complexity), so there is no reason not to use it in all cases. """ # Constants in Chudnovsky's series CHUD_A = MPZ(13591409) CHUD_B = MPZ(545140134) CHUD_C = MPZ(640320) CHUD_D = MPZ(12) def bs_chudnovsky(a, b, level, verbose): """ Computes the sum from a to b of the series in the Chudnovsky formula. Returns g, p, q where p/q is the sum as an exact fraction and g is a temporary value used to save work for recursive calls. """ if b-a == 1: g = MPZ((6*b-5)*(2*b-1)*(6*b-1)) p = b**3 * CHUD_C**3 // 24 q = (-1)**b * g * (CHUD_A+CHUD_B*b) else: if verbose and level < 4: print(" binary splitting", a, b) mid = (a+b)//2 g1, p1, q1 = bs_chudnovsky(a, mid, level+1, verbose) g2, p2, q2 = bs_chudnovsky(mid, b, level+1, verbose) p = p1*p2 g = g1*g2 q = q1*p2 + q2*g1 return g, p, q @constant_memo def pi_fixed(prec, verbose=False, verbose_base=None): """ Compute floor(pi * 2**prec) as a big integer. This is done using Chudnovsky's series (see comments in libelefun.py for details). """ # The Chudnovsky series gives 14.18 digits per term N = int(prec/3.3219280948/14.181647462 + 2) if verbose: print("binary splitting with N =", N) g, p, q = bs_chudnovsky(0, N, 0, verbose) sqrtC = isqrt_fast(CHUD_C<<(2*prec)) v = p*CHUD_C*sqrtC//((q+CHUD_A*p)*CHUD_D) return v def degree_fixed(prec): return pi_fixed(prec)//180 def bspe(a, b): """ Sum series for exp(1)-1 between a, b, returning the result as an exact fraction (p, q). """ if b-a == 1: return MPZ_ONE, MPZ(b) m = (a+b)//2 p1, q1 = bspe(a, m) p2, q2 = bspe(m, b) return p1*q2+p2, q1*q2 @constant_memo def e_fixed(prec): """ Computes exp(1). This is done using the ordinary Taylor series for exp, with binary splitting. For a description of the algorithm, see: http://numbers.computation.free.fr/Constants/ Algorithms/splitting.html """ # Slight overestimate of N needed for 1/N! < 2**(-prec) # This could be tightened for large N. N = int(1.1*prec/math.log(prec) + 20) p, q = bspe(0,N) return ((p+q)<<prec)//q @constant_memo def phi_fixed(prec): """ Computes the golden ratio, (1+sqrt(5))/2 """ prec += 10 a = isqrt_fast(MPZ_FIVE<<(2*prec)) + (MPZ_ONE << prec) return a >> 11 mpf_phi = def_mpf_constant(phi_fixed) mpf_pi = def_mpf_constant(pi_fixed) mpf_e = def_mpf_constant(e_fixed) mpf_degree = def_mpf_constant(degree_fixed) mpf_ln2 = def_mpf_constant(ln2_fixed) mpf_ln10 = def_mpf_constant(ln10_fixed) @constant_memo def ln_sqrt2pi_fixed(prec): wp = prec + 10 # ln(sqrt(2*pi)) = ln(2*pi)/2 return to_fixed(mpf_log(mpf_shift(mpf_pi(wp), 1), wp), prec-1) @constant_memo def sqrtpi_fixed(prec): return sqrt_fixed(pi_fixed(prec), prec) mpf_sqrtpi = def_mpf_constant(sqrtpi_fixed) mpf_ln_sqrt2pi = def_mpf_constant(ln_sqrt2pi_fixed) #----------------------------------------------------------------------------# # # # Powers # # # #----------------------------------------------------------------------------# def mpf_pow(s, t, prec, rnd=round_fast): """ Compute s**t. Raises ComplexResult if s is negative and t is fractional. """ ssign, sman, sexp, sbc = s tsign, tman, texp, tbc = t if ssign and texp < 0: raise ComplexResult("negative number raised to a fractional power") if texp >= 0: return mpf_pow_int(s, (-1)**tsign * (tman<<texp), prec, rnd) # s**(n/2) = sqrt(s)**n if texp == -1: if tman == 1: if tsign: return mpf_div(fone, mpf_sqrt(s, prec+10, reciprocal_rnd[rnd]), prec, rnd) return mpf_sqrt(s, prec, rnd) else: if tsign: return mpf_pow_int(mpf_sqrt(s, prec+10, reciprocal_rnd[rnd]), -tman, prec, rnd) return mpf_pow_int(mpf_sqrt(s, prec+10, rnd), tman, prec, rnd) # General formula: s**t = exp(t*log(s)) # TODO: handle rnd direction of the logarithm carefully c = mpf_log(s, prec+10, rnd) return mpf_exp(mpf_mul(t, c), prec, rnd) def int_pow_fixed(y, n, prec): """n-th power of a fixed point number with precision prec Returns the power in the form man, exp, man * 2**exp ~= y**n """ if n == 2: return (y*y), 0 bc = bitcount(y) exp = 0 workprec = 2 * (prec + 4*bitcount(n) + 4) _, pm, pe, pbc = fone while 1: if n & 1: pm = pm*y pe = pe+exp pbc += bc - 2 pbc = pbc + bctable[int(pm >> pbc)] if pbc > workprec: pm = pm >> (pbc-workprec) pe += pbc - workprec pbc = workprec n -= 1 if not n: break y = y*y exp = exp+exp bc = bc + bc - 2 bc = bc + bctable[int(y >> bc)] if bc > workprec: y = y >> (bc-workprec) exp += bc - workprec bc = workprec n = n // 2 return pm, pe # froot(s, n, prec, rnd) computes the real n-th root of a # positive mpf tuple s. # To compute the root we start from a 50-bit estimate for r # generated with ordinary floating-point arithmetic, and then refine # the value to full accuracy using the iteration # 1 / y \ # r = --- | (n-1) * r + ---------- | # n+1 n \ n r_n**(n-1) / # which is simply Newton's method applied to the equation r**n = y. # With giant_steps(start, prec+extra) = [p0,...,pm, prec+extra] # and y = man * 2**-shift one has # (man * 2**exp)**(1/n) = # y**(1/n) * 2**(start-prec/n) * 2**(p0-start) * ... * 2**(prec+extra-pm) * # 2**((exp+shift-(n-1)*prec)/n -extra)) # The last factor is accounted for in the last line of froot. def nthroot_fixed(y, n, prec, exp1): start = 50 try: y1 = rshift(y, prec - n*start) r = MPZ(int(y1**(1.0/n))) except OverflowError: y1 = from_int(y1, start) fn = from_int(n) fn = mpf_rdiv_int(1, fn, start) r = mpf_pow(y1, fn, start) r = to_int(r) extra = 10 extra1 = n prevp = start for p in giant_steps(start, prec+extra): pm, pe = int_pow_fixed(r, n-1, prevp) r2 = rshift(pm, (n-1)*prevp - p - pe - extra1) B = lshift(y, 2*p-prec+extra1)//r2 r = (B + (n-1) * lshift(r, p-prevp))//n prevp = p return r def mpf_nthroot(s, n, prec, rnd=round_fast): """nth-root of a positive number Use the Newton method when faster, otherwise use x**(1/n) """ sign, man, exp, bc = s if sign: raise ComplexResult("nth root of a negative number") if not man: if s == fnan: return fnan if s == fzero: if n > 0: return fzero if n == 0: return fone return finf # Infinity if not n: return fnan if n < 0: return fzero return finf flag_inverse = False if n < 2: if n == 0: return fone if n == 1: return mpf_pos(s, prec, rnd) if n == -1: return mpf_div(fone, s, prec, rnd) # n < 0 rnd = reciprocal_rnd[rnd] flag_inverse = True extra_inverse = 5 prec += extra_inverse n = -n if n > 20 and (n >= 20000 or prec < int(233 + 28.3 * n**0.62)): prec2 = prec + 10 fn = from_int(n) nth = mpf_rdiv_int(1, fn, prec2) r = mpf_pow(s, nth, prec2, rnd) s = normalize(r[0], r[1], r[2], r[3], prec, rnd) if flag_inverse: return mpf_div(fone, s, prec-extra_inverse, rnd) else: return s # Convert to a fixed-point number with prec2 bits. prec2 = prec + 2*n - (prec%n) # a few tests indicate that # for 10 < n < 10**4 a bit more precision is needed if n > 10: prec2 += prec2//10 prec2 = prec2 - prec2%n # Mantissa may have more bits than we need. Trim it down. shift = bc - prec2 # Adjust exponents to make prec2 and exp+shift multiples of n. sign1 = 0 es = exp+shift if es < 0: sign1 = 1 es = -es if sign1: shift += es%n else: shift -= es%n man = rshift(man, shift) extra = 10 exp1 = ((exp+shift-(n-1)*prec2)//n) - extra rnd_shift = 0 if flag_inverse: if rnd == 'u' or rnd == 'c': rnd_shift = 1 else: if rnd == 'd' or rnd == 'f': rnd_shift = 1 man = nthroot_fixed(man+rnd_shift, n, prec2, exp1) s = from_man_exp(man, exp1, prec, rnd) if flag_inverse: return mpf_div(fone, s, prec-extra_inverse, rnd) else: return s def mpf_cbrt(s, prec, rnd=round_fast): """cubic root of a positive number""" return mpf_nthroot(s, 3, prec, rnd) #----------------------------------------------------------------------------# # # # Logarithms # # # #----------------------------------------------------------------------------# def log_int_fixed(n, prec, ln2=None): """ Fast computation of log(n), caching the value for small n, intended for zeta sums. """ if n in log_int_cache: value, vprec = log_int_cache[n] if vprec >= prec: return value >> (vprec - prec) wp = prec + 10 if wp <= LOG_TAYLOR_SHIFT: if ln2 is None: ln2 = ln2_fixed(wp) r = bitcount(n) x = n << (wp-r) v = log_taylor_cached(x, wp) + r*ln2 else: v = to_fixed(mpf_log(from_int(n), wp+5), wp) if n < MAX_LOG_INT_CACHE: log_int_cache[n] = (v, wp) return v >> (wp-prec) def agm_fixed(a, b, prec): """ Fixed-point computation of agm(a,b), assuming a, b both close to unit magnitude. """ i = 0 while 1: anew = (a+b)>>1 if i > 4 and abs(a-anew) < 8: return a b = isqrt_fast(a*b) a = anew i += 1 return a def log_agm(x, prec): """ Fixed-point computation of -log(x) = log(1/x), suitable for large precision. It is required that 0 < x < 1. The algorithm used is the Sasaki-Kanada formula -log(x) = pi/agm(theta2(x)^2,theta3(x)^2). [1] For faster convergence in the theta functions, x should be chosen closer to 0. Guard bits must be added by the caller. HYPOTHESIS: if x = 2^(-n), n bits need to be added to account for the truncation to a fixed-point number, and this is the only significant cancellation error. The number of bits lost to roundoff is small and can be considered constant. [1] Richard P. Brent, "Fast Algorithms for High-Precision Computation of Elementary Functions (extended abstract)", http://wwwmaths.anu.edu.au/~brent/pd/RNC7-Brent.pdf """ x2 = (x*x) >> prec # Compute jtheta2(x)**2 s = a = b = x2 while a: b = (b*x2) >> prec a = (a*b) >> prec s += a s += (MPZ_ONE<<prec) s = (s*s)>>(prec-2) s = (s*isqrt_fast(x<<prec))>>prec # Compute jtheta3(x)**2 t = a = b = x while a: b = (b*x2) >> prec a = (a*b) >> prec t += a t = (MPZ_ONE<<prec) + (t<<1) t = (t*t)>>prec # Final formula p = agm_fixed(s, t, prec) return (pi_fixed(prec) << prec) // p def log_taylor(x, prec, r=0): """ Fixed-point calculation of log(x). It is assumed that x is close enough to 1 for the Taylor series to converge quickly. Convergence can be improved by specifying r > 0 to compute log(x^(1/2^r))*2^r, at the cost of performing r square roots. The caller must provide sufficient guard bits. """ for i in xrange(r): x = isqrt_fast(x<<prec) one = MPZ_ONE << prec v = ((x-one)<<prec)//(x+one) sign = v < 0 if sign: v = -v v2 = (v*v) >> prec v4 = (v2*v2) >> prec s0 = v s1 = v//3 v = (v*v4) >> prec k = 5 while v: s0 += v // k k += 2 s1 += v // k v = (v*v4) >> prec k += 2 s1 = (s1*v2) >> prec s = (s0+s1) << (1+r) if sign: return -s return s def log_taylor_cached(x, prec): """ Fixed-point computation of log(x), assuming x in (0.5, 2) and prec <= LOG_TAYLOR_PREC. """ n = x >> (prec-LOG_TAYLOR_SHIFT) cached_prec = cache_prec_steps[prec] dprec = cached_prec - prec if (n, cached_prec) in log_taylor_cache: a, log_a = log_taylor_cache[n, cached_prec] else: a = n << (cached_prec - LOG_TAYLOR_SHIFT) log_a = log_taylor(a, cached_prec, 8) log_taylor_cache[n, cached_prec] = (a, log_a) a >>= dprec log_a >>= dprec u = ((x - a) << prec) // a v = (u << prec) // ((MPZ_TWO << prec) + u) v2 = (v*v) >> prec v4 = (v2*v2) >> prec s0 = v s1 = v//3 v = (v*v4) >> prec k = 5 while v: s0 += v//k k += 2 s1 += v//k v = (v*v4) >> prec k += 2 s1 = (s1*v2) >> prec s = (s0+s1) << 1 return log_a + s def mpf_log(x, prec, rnd=round_fast): """ Compute the natural logarithm of the mpf value x. If x is negative, ComplexResult is raised. """ sign, man, exp, bc = x #------------------------------------------------------------------ # Handle special values if not man: if x == fzero: return fninf if x == finf: return finf if x == fnan: return fnan if sign: raise ComplexResult("logarithm of a negative number") wp = prec + 20 #------------------------------------------------------------------ # Handle log(2^n) = log(n)*2. # Here we catch the only possible exact value, log(1) = 0 if man == 1: if not exp: return fzero return from_man_exp(exp*ln2_fixed(wp), -wp, prec, rnd) mag = exp+bc abs_mag = abs(mag) #------------------------------------------------------------------ # Handle x = 1+eps, where log(x) ~ x. We need to check for # cancellation when moving to fixed-point math and compensate # by increasing the precision. Note that abs_mag in (0, 1) <=> # 0.5 < x < 2 and x != 1 if abs_mag <= 1: # Calculate t = x-1 to measure distance from 1 in bits tsign = 1-abs_mag if tsign: tman = (MPZ_ONE<<bc) - man else: tman = man - (MPZ_ONE<<(bc-1)) tbc = bitcount(tman) cancellation = bc - tbc if cancellation > wp: t = normalize(tsign, tman, abs_mag-bc, tbc, tbc, 'n') return mpf_perturb(t, tsign, prec, rnd) else: wp += cancellation # TODO: if close enough to 1, we could use Taylor series # even in the AGM precision range, since the Taylor series # converges rapidly #------------------------------------------------------------------ # Another special case: # n*log(2) is a good enough approximation if abs_mag > 10000: if bitcount(abs_mag) > wp: return from_man_exp(exp*ln2_fixed(wp), -wp, prec, rnd) #------------------------------------------------------------------ # General case. # Perform argument reduction using log(x) = log(x*2^n) - n*log(2): # If we are in the Taylor precision range, choose magnitude 0 or 1. # If we are in the AGM precision range, choose magnitude -m for # some large m; benchmarking on one machine showed m = prec/20 to be # optimal between 1000 and 100,000 digits. if wp <= LOG_TAYLOR_PREC: m = log_taylor_cached(lshift(man, wp-bc), wp) if mag: m += mag*ln2_fixed(wp) else: optimal_mag = -wp//LOG_AGM_MAG_PREC_RATIO n = optimal_mag - mag x = mpf_shift(x, n) wp += (-optimal_mag) m = -log_agm(to_fixed(x, wp), wp) m -= n*ln2_fixed(wp) return from_man_exp(m, -wp, prec, rnd) def mpf_log_hypot(a, b, prec, rnd): """ Computes log(sqrt(a^2+b^2)) accurately. """ # If either a or b is inf/nan/0, assume it to be a if not b[1]: a, b = b, a # a is inf/nan/0 if not a[1]: # both are inf/nan/0 if not b[1]: if a == b == fzero: return fninf if fnan in (a, b): return fnan # at least one term is (+/- inf)^2 return finf # only a is inf/nan/0 if a == fzero: # log(sqrt(0+b^2)) = log(|b|) return mpf_log(mpf_abs(b), prec, rnd) if a == fnan: return fnan return finf # Exact a2 = mpf_mul(a,a) b2 = mpf_mul(b,b) extra = 20 # Not exact h2 = mpf_add(a2, b2, prec+extra) cancelled = mpf_add(h2, fnone, 10) mag_cancelled = cancelled[2]+cancelled[3] # Just redo the sum exactly if necessary (could be smarter # and avoid memory allocation when a or b is precisely 1 # and the other is tiny...) if cancelled == fzero or mag_cancelled < -extra//2: h2 = mpf_add(a2, b2, prec+extra-min(a2[2],b2[2])) return mpf_shift(mpf_log(h2, prec, rnd), -1) #---------------------------------------------------------------------- # Inverse tangent # def atan_newton(x, prec): if prec >= 100: r = math.atan(int((x>>(prec-53)))/2.0**53) else: r = math.atan(int(x)/2.0**prec) prevp = 50 r = MPZ(int(r * 2.0**53) >> (53-prevp)) extra_p = 50 for wp in giant_steps(prevp, prec): wp += extra_p r = r << (wp-prevp) cos, sin = cos_sin_fixed(r, wp) tan = (sin << wp) // cos a = ((tan-rshift(x, prec-wp)) << wp) // ((MPZ_ONE<<wp) + ((tan**2)>>wp)) r = r - a prevp = wp return rshift(r, prevp-prec) def atan_taylor_get_cached(n, prec): # Taylor series with caching wins up to huge precisions # To avoid unnecessary precomputation at low precision, we # do it in steps # Round to next power of 2 prec2 = (1<<(bitcount(prec-1))) + 20 dprec = prec2 - prec if (n, prec2) in atan_taylor_cache: a, atan_a = atan_taylor_cache[n, prec2] else: a = n << (prec2 - ATAN_TAYLOR_SHIFT) atan_a = atan_newton(a, prec2) atan_taylor_cache[n, prec2] = (a, atan_a) return (a >> dprec), (atan_a >> dprec) def atan_taylor(x, prec): n = (x >> (prec-ATAN_TAYLOR_SHIFT)) a, atan_a = atan_taylor_get_cached(n, prec) d = x - a s0 = v = (d << prec) // ((a**2 >> prec) + (a*d >> prec) + (MPZ_ONE << prec)) v2 = (v**2 >> prec) v4 = (v2 * v2) >> prec s1 = v//3 v = (v * v4) >> prec k = 5 while v: s0 += v // k k += 2 s1 += v // k v = (v * v4) >> prec k += 2 s1 = (s1 * v2) >> prec s = s0 - s1 return atan_a + s def atan_inf(sign, prec, rnd): if not sign: return mpf_shift(mpf_pi(prec, rnd), -1) return mpf_neg(mpf_shift(mpf_pi(prec, negative_rnd[rnd]), -1)) def mpf_atan(x, prec, rnd=round_fast): sign, man, exp, bc = x if not man: if x == fzero: return fzero if x == finf: return atan_inf(0, prec, rnd) if x == fninf: return atan_inf(1, prec, rnd) return fnan mag = exp + bc # Essentially infinity if mag > prec+20: return atan_inf(sign, prec, rnd) # Essentially ~ x if -mag > prec+20: return mpf_perturb(x, 1-sign, prec, rnd) wp = prec + 30 + abs(mag) # For large x, use atan(x) = pi/2 - atan(1/x) if mag >= 2: x = mpf_rdiv_int(1, x, wp) reciprocal = True else: reciprocal = False t = to_fixed(x, wp) if sign: t = -t if wp < ATAN_TAYLOR_PREC: a = atan_taylor(t, wp) else: a = atan_newton(t, wp) if reciprocal: a = ((pi_fixed(wp)>>1)+1) - a if sign: a = -a return from_man_exp(a, -wp, prec, rnd) # TODO: cleanup the special cases def mpf_atan2(y, x, prec, rnd=round_fast): xsign, xman, xexp, xbc = x ysign, yman, yexp, ybc = y if not yman: if y == fzero and x != fnan: if mpf_sign(x) >= 0: return fzero return mpf_pi(prec, rnd) if y in (finf, fninf): if x in (finf, fninf): return fnan # pi/2 if y == finf: return mpf_shift(mpf_pi(prec, rnd), -1) # -pi/2 return mpf_neg(mpf_shift(mpf_pi(prec, negative_rnd[rnd]), -1)) return fnan if ysign: return mpf_neg(mpf_atan2(mpf_neg(y), x, prec, negative_rnd[rnd])) if not xman: if x == fnan: return fnan if x == finf: return fzero if x == fninf: return mpf_pi(prec, rnd) if y == fzero: return fzero return mpf_shift(mpf_pi(prec, rnd), -1) tquo = mpf_atan(mpf_div(y, x, prec+4), prec+4) if xsign: return mpf_add(mpf_pi(prec+4), tquo, prec, rnd) else: return mpf_pos(tquo, prec, rnd) def mpf_asin(x, prec, rnd=round_fast): sign, man, exp, bc = x if bc+exp > 0 and x not in (fone, fnone): raise ComplexResult("asin(x) is real only for -1 <= x <= 1") # asin(x) = 2*atan(x/(1+sqrt(1-x**2))) wp = prec + 15 a = mpf_mul(x, x) b = mpf_add(fone, mpf_sqrt(mpf_sub(fone, a, wp), wp), wp) c = mpf_div(x, b, wp) return mpf_shift(mpf_atan(c, prec, rnd), 1) def mpf_acos(x, prec, rnd=round_fast): # acos(x) = 2*atan(sqrt(1-x**2)/(1+x)) sign, man, exp, bc = x if bc + exp > 0: if x not in (fone, fnone): raise ComplexResult("acos(x) is real only for -1 <= x <= 1") if x == fnone: return mpf_pi(prec, rnd) wp = prec + 15 a = mpf_mul(x, x) b = mpf_sqrt(mpf_sub(fone, a, wp), wp) c = mpf_div(b, mpf_add(fone, x, wp), wp) return mpf_shift(mpf_atan(c, prec, rnd), 1) def mpf_asinh(x, prec, rnd=round_fast): wp = prec + 20 sign, man, exp, bc = x mag = exp+bc if mag < -8: if mag < -wp: return mpf_perturb(x, 1-sign, prec, rnd) wp += (-mag) # asinh(x) = log(x+sqrt(x**2+1)) # use reflection symmetry to avoid cancellation q = mpf_sqrt(mpf_add(mpf_mul(x, x), fone, wp), wp) q = mpf_add(mpf_abs(x), q, wp) if sign: return mpf_neg(mpf_log(q, prec, negative_rnd[rnd])) else: return mpf_log(q, prec, rnd) def mpf_acosh(x, prec, rnd=round_fast): # acosh(x) = log(x+sqrt(x**2-1)) wp = prec + 15 if mpf_cmp(x, fone) == -1: raise ComplexResult("acosh(x) is real only for x >= 1") q = mpf_sqrt(mpf_add(mpf_mul(x,x), fnone, wp), wp) return mpf_log(mpf_add(x, q, wp), prec, rnd) def mpf_atanh(x, prec, rnd=round_fast): # atanh(x) = log((1+x)/(1-x))/2 sign, man, exp, bc = x if (not man) and exp: if x in (fzero, fnan): return x raise ComplexResult("atanh(x) is real only for -1 <= x <= 1") mag = bc + exp if mag > 0: if mag == 1 and man == 1: return [finf, fninf][sign] raise ComplexResult("atanh(x) is real only for -1 <= x <= 1") wp = prec + 15 if mag < -8: if mag < -wp: return mpf_perturb(x, sign, prec, rnd) wp += (-mag) a = mpf_add(x, fone, wp) b = mpf_sub(fone, x, wp) return mpf_shift(mpf_log(mpf_div(a, b, wp), prec, rnd), -1) def mpf_fibonacci(x, prec, rnd=round_fast): sign, man, exp, bc = x if not man: if x == fninf: return fnan return x # F(2^n) ~= 2^(2^n) size = abs(exp+bc) if exp >= 0: # Exact if size < 10 or size <= bitcount(prec): return from_int(ifib(to_int(x)), prec, rnd) # Use the modified Binet formula wp = prec + size + 20 a = mpf_phi(wp) b = mpf_add(mpf_shift(a, 1), fnone, wp) u = mpf_pow(a, x, wp) v = mpf_cos_pi(x, wp) v = mpf_div(v, u, wp) u = mpf_sub(u, v, wp) u = mpf_div(u, b, prec, rnd) return u #------------------------------------------------------------------------------- # Exponential-type functions #------------------------------------------------------------------------------- def exponential_series(x, prec, type=0): """ Taylor series for cosh/sinh or cos/sin. type = 0 -- returns exp(x) (slightly faster than cosh+sinh) type = 1 -- returns (cosh(x), sinh(x)) type = 2 -- returns (cos(x), sin(x)) """ if x < 0: x = -x sign = 1 else: sign = 0 r = int(0.5*prec**0.5) xmag = bitcount(x) - prec r = max(0, xmag + r) extra = 10 + 2*max(r,-xmag) wp = prec + extra x <<= (extra - r) one = MPZ_ONE << wp alt = (type == 2) if prec < EXP_SERIES_U_CUTOFF: x2 = a = (x*x) >> wp x4 = (x2*x2) >> wp s0 = s1 = MPZ_ZERO k = 2 while a: a //= (k-1)*k; s0 += a; k += 2 a //= (k-1)*k; s1 += a; k += 2 a = (a*x4) >> wp s1 = (x2*s1) >> wp if alt: c = s1 - s0 + one else: c = s1 + s0 + one else: u = int(0.3*prec**0.35) x2 = a = (x*x) >> wp xpowers = [one, x2] for i in xrange(1, u): xpowers.append((xpowers[-1]*x2)>>wp) sums = [MPZ_ZERO] * u k = 2 while a: for i in xrange(u): a //= (k-1)*k if alt and k & 2: sums[i] -= a else: sums[i] += a k += 2 a = (a*xpowers[-1]) >> wp for i in xrange(1, u): sums[i] = (sums[i]*xpowers[i]) >> wp c = sum(sums) + one if type == 0: s = isqrt_fast(c*c - (one<<wp)) if sign: v = c - s else: v = c + s for i in xrange(r): v = (v*v) >> wp return v >> extra else: # Repeatedly apply the double-angle formula # cosh(2*x) = 2*cosh(x)^2 - 1 # cos(2*x) = 2*cos(x)^2 - 1 pshift = wp-1 for i in xrange(r): c = ((c*c) >> pshift) - one # With the abs, this is the same for sinh and sin s = isqrt_fast(abs((one<<wp) - c*c)) if sign: s = -s return (c>>extra), (s>>extra) def exp_basecase(x, prec): """ Compute exp(x) as a fixed-point number. Works for any x, but for speed should have |x| < 1. For an arbitrary number, use exp(x) = exp(x-m*log(2)) * 2^m where m = floor(x/log(2)). """ if prec > EXP_COSH_CUTOFF: return exponential_series(x, prec, 0) r = int(prec**0.5) prec += r s0 = s1 = (MPZ_ONE << prec) k = 2 a = x2 = (x*x) >> prec while a: a //= k; s0 += a; k += 1 a //= k; s1 += a; k += 1 a = (a*x2) >> prec s1 = (s1*x) >> prec s = s0 + s1 u = r while r: s = (s*s) >> prec r -= 1 return s >> u def exp_expneg_basecase(x, prec): """ Computation of exp(x), exp(-x) """ if prec > EXP_COSH_CUTOFF: cosh, sinh = exponential_series(x, prec, 1) return cosh+sinh, cosh-sinh a = exp_basecase(x, prec) b = (MPZ_ONE << (prec+prec)) // a return a, b def cos_sin_basecase(x, prec): """ Compute cos(x), sin(x) as fixed-point numbers, assuming x in [0, pi/2). For an arbitrary number, use x' = x - m*(pi/2) where m = floor(x/(pi/2)) along with quarter-period symmetries. """ if prec > COS_SIN_CACHE_PREC: return exponential_series(x, prec, 2) precs = prec - COS_SIN_CACHE_STEP t = x >> precs n = int(t) if n not in cos_sin_cache: w = t<<(10+COS_SIN_CACHE_PREC-COS_SIN_CACHE_STEP) cos_t, sin_t = exponential_series(w, 10+COS_SIN_CACHE_PREC, 2) cos_sin_cache[n] = (cos_t>>10), (sin_t>>10) cos_t, sin_t = cos_sin_cache[n] offset = COS_SIN_CACHE_PREC - prec cos_t >>= offset sin_t >>= offset x -= t << precs cos = MPZ_ONE << prec sin = x k = 2 a = -((x*x) >> prec) while a: a //= k; cos += a; k += 1; a = (a*x) >> prec a //= k; sin += a; k += 1; a = -((a*x) >> prec) return ((cos*cos_t-sin*sin_t) >> prec), ((sin*cos_t+cos*sin_t) >> prec) def mpf_exp(x, prec, rnd=round_fast): sign, man, exp, bc = x if man: mag = bc + exp wp = prec + 14 if sign: man = -man # TODO: the best cutoff depends on both x and the precision. if prec > 600 and exp >= 0: # Need about log2(exp(n)) ~= 1.45*mag extra precision e = mpf_e(wp+int(1.45*mag)) return mpf_pow_int(e, man<<exp, prec, rnd) if mag < -wp: return mpf_perturb(fone, sign, prec, rnd) # |x| >= 2 if mag > 1: # For large arguments: exp(2^mag*(1+eps)) = # exp(2^mag)*exp(2^mag*eps) = exp(2^mag)*(1 + 2^mag*eps + ...) # so about mag extra bits is required. wpmod = wp + mag offset = exp + wpmod if offset >= 0: t = man << offset else: t = man >> (-offset) lg2 = ln2_fixed(wpmod) n, t = divmod(t, lg2) n = int(n) t >>= mag else: offset = exp + wp if offset >= 0: t = man << offset else: t = man >> (-offset) n = 0 man = exp_basecase(t, wp) return from_man_exp(man, n-wp, prec, rnd) if not exp: return fone if x == fninf: return fzero return x def mpf_cosh_sinh(x, prec, rnd=round_fast, tanh=0): """Simultaneously compute (cosh(x), sinh(x)) for real x""" sign, man, exp, bc = x if (not man) and exp: if tanh: if x == finf: return fone if x == fninf: return fnone return fnan if x == finf: return (finf, finf) if x == fninf: return (finf, fninf) return fnan, fnan mag = exp+bc wp = prec+14 if mag < -4: # Extremely close to 0, sinh(x) ~= x and cosh(x) ~= 1 if mag < -wp: if tanh: return mpf_perturb(x, 1-sign, prec, rnd) cosh = mpf_perturb(fone, 0, prec, rnd) sinh = mpf_perturb(x, sign, prec, rnd) return cosh, sinh # Fix for cancellation when computing sinh wp += (-mag) # Does exp(-2*x) vanish? if mag > 10: if 3*(1<<(mag-1)) > wp: # XXX: rounding if tanh: return mpf_perturb([fone,fnone][sign], 1-sign, prec, rnd) c = s = mpf_shift(mpf_exp(mpf_abs(x), prec, rnd), -1) if sign: s = mpf_neg(s) return c, s # |x| > 1 if mag > 1: wpmod = wp + mag offset = exp + wpmod if offset >= 0: t = man << offset else: t = man >> (-offset) lg2 = ln2_fixed(wpmod) n, t = divmod(t, lg2) n = int(n) t >>= mag else: offset = exp + wp if offset >= 0: t = man << offset else: t = man >> (-offset) n = 0 a, b = exp_expneg_basecase(t, wp) # TODO: optimize division precision cosh = a + (b>>(2*n)) sinh = a - (b>>(2*n)) if sign: sinh = -sinh if tanh: man = (sinh << wp) // cosh return from_man_exp(man, -wp, prec, rnd) else: cosh = from_man_exp(cosh, n-wp-1, prec, rnd) sinh = from_man_exp(sinh, n-wp-1, prec, rnd) return cosh, sinh def mod_pi2(man, exp, mag, wp): # Reduce to standard interval if mag > 0: i = 0 while 1: cancellation_prec = 20 << i wpmod = wp + mag + cancellation_prec pi2 = pi_fixed(wpmod-1) pi4 = pi2 >> 1 offset = wpmod + exp if offset >= 0: t = man << offset else: t = man >> (-offset) n, y = divmod(t, pi2) if y > pi4: small = pi2 - y else: small = y if small >> (wp+mag-10): n = int(n) t = y >> mag wp = wpmod - mag break i += 1 else: wp += (-mag) offset = exp + wp if offset >= 0: t = man << offset else: t = man >> (-offset) n = 0 return t, n, wp def mpf_cos_sin(x, prec, rnd=round_fast, which=0, pi=False): """ which: 0 -- return cos(x), sin(x) 1 -- return cos(x) 2 -- return sin(x) 3 -- return tan(x) if pi=True, compute for pi*x """ sign, man, exp, bc = x if not man: if exp: c, s = fnan, fnan else: c, s = fone, fzero if which == 0: return c, s if which == 1: return c if which == 2: return s if which == 3: return s mag = bc + exp wp = prec + 10 # Extremely small? if mag < 0: if mag < -wp: if pi: x = mpf_mul(x, mpf_pi(wp)) c = mpf_perturb(fone, 1, prec, rnd) s = mpf_perturb(x, 1-sign, prec, rnd) if which == 0: return c, s if which == 1: return c if which == 2: return s if which == 3: return mpf_perturb(x, sign, prec, rnd) if pi: if exp >= -1: if exp == -1: c = fzero s = (fone, fnone)[bool(man & 2) ^ sign] elif exp == 0: c, s = (fnone, fzero) else: c, s = (fone, fzero) if which == 0: return c, s if which == 1: return c if which == 2: return s if which == 3: return mpf_div(s, c, prec, rnd) # Subtract nearest half-integer (= mod by pi/2) n = ((man >> (-exp-2)) + 1) >> 1 man = man - (n << (-exp-1)) mag2 = bitcount(man) + exp wp = prec + 10 - mag2 offset = exp + wp if offset >= 0: t = man << offset else: t = man >> (-offset) t = (t*pi_fixed(wp)) >> wp else: t, n, wp = mod_pi2(man, exp, mag, wp) c, s = cos_sin_basecase(t, wp) m = n & 3 if m == 1: c, s = -s, c elif m == 2: c, s = -c, -s elif m == 3: c, s = s, -c if sign: s = -s if which == 0: c = from_man_exp(c, -wp, prec, rnd) s = from_man_exp(s, -wp, prec, rnd) return c, s if which == 1: return from_man_exp(c, -wp, prec, rnd) if which == 2: return from_man_exp(s, -wp, prec, rnd) if which == 3: return from_rational(s, c, prec, rnd) def mpf_cos(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 1) def mpf_sin(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 2) def mpf_tan(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 3) def mpf_cos_sin_pi(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 0, 1) def mpf_cos_pi(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 1, 1) def mpf_sin_pi(x, prec, rnd=round_fast): return mpf_cos_sin(x, prec, rnd, 2, 1) def mpf_cosh(x, prec, rnd=round_fast): return mpf_cosh_sinh(x, prec, rnd)[0] def mpf_sinh(x, prec, rnd=round_fast): return mpf_cosh_sinh(x, prec, rnd)[1] def mpf_tanh(x, prec, rnd=round_fast): return mpf_cosh_sinh(x, prec, rnd, tanh=1) # Low-overhead fixed-point versions def cos_sin_fixed(x, prec, pi2=None): if pi2 is None: pi2 = pi_fixed(prec-1) n, t = divmod(x, pi2) n = int(n) c, s = cos_sin_basecase(t, prec) m = n & 3 if m == 0: return c, s if m == 1: return -s, c if m == 2: return -c, -s if m == 3: return s, -c def exp_fixed(x, prec, ln2=None): if ln2 is None: ln2 = ln2_fixed(prec) n, t = divmod(x, ln2) n = int(n) v = exp_basecase(t, prec) if n >= 0: return v << n else: return v >> (-n) if BACKEND == 'sage': try: import sage.libs.mpmath.ext_libmp as _lbmp mpf_sqrt = _lbmp.mpf_sqrt mpf_exp = _lbmp.mpf_exp mpf_log = _lbmp.mpf_log mpf_cos = _lbmp.mpf_cos mpf_sin = _lbmp.mpf_sin mpf_pow = _lbmp.mpf_pow exp_fixed = _lbmp.exp_fixed cos_sin_fixed = _lbmp.cos_sin_fixed log_int_fixed = _lbmp.log_int_fixed except (ImportError, AttributeError): print("Warning: Sage imports in libelefun failed")
43,860
29.693492
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/libmpi.py
""" Computational functions for interval arithmetic. """ from .backend import xrange from .libmpf import ( ComplexResult, round_down, round_up, round_floor, round_ceiling, round_nearest, prec_to_dps, repr_dps, dps_to_prec, bitcount, from_float, fnan, finf, fninf, fzero, fhalf, fone, fnone, mpf_sign, mpf_lt, mpf_le, mpf_gt, mpf_ge, mpf_eq, mpf_cmp, mpf_min_max, mpf_floor, from_int, to_int, to_str, from_str, mpf_abs, mpf_neg, mpf_pos, mpf_add, mpf_sub, mpf_mul, mpf_mul_int, mpf_div, mpf_shift, mpf_pow_int, from_man_exp, MPZ_ONE) from .libelefun import ( mpf_log, mpf_exp, mpf_sqrt, mpf_atan, mpf_atan2, mpf_pi, mod_pi2, mpf_cos_sin ) from .gammazeta import mpf_gamma, mpf_rgamma, mpf_loggamma, mpc_loggamma def mpi_str(s, prec): sa, sb = s dps = prec_to_dps(prec) + 5 return "[%s, %s]" % (to_str(sa, dps), to_str(sb, dps)) #dps = prec_to_dps(prec) #m = mpi_mid(s, prec) #d = mpf_shift(mpi_delta(s, 20), -1) #return "%s +/- %s" % (to_str(m, dps), to_str(d, 3)) mpi_zero = (fzero, fzero) mpi_one = (fone, fone) def mpi_eq(s, t): return s == t def mpi_ne(s, t): return s != t def mpi_lt(s, t): sa, sb = s ta, tb = t if mpf_lt(sb, ta): return True if mpf_ge(sa, tb): return False return None def mpi_le(s, t): sa, sb = s ta, tb = t if mpf_le(sb, ta): return True if mpf_gt(sa, tb): return False return None def mpi_gt(s, t): return mpi_lt(t, s) def mpi_ge(s, t): return mpi_le(t, s) def mpi_add(s, t, prec=0): sa, sb = s ta, tb = t a = mpf_add(sa, ta, prec, round_floor) b = mpf_add(sb, tb, prec, round_ceiling) if a == fnan: a = fninf if b == fnan: b = finf return a, b def mpi_sub(s, t, prec=0): sa, sb = s ta, tb = t a = mpf_sub(sa, tb, prec, round_floor) b = mpf_sub(sb, ta, prec, round_ceiling) if a == fnan: a = fninf if b == fnan: b = finf return a, b def mpi_delta(s, prec): sa, sb = s return mpf_sub(sb, sa, prec, round_up) def mpi_mid(s, prec): sa, sb = s return mpf_shift(mpf_add(sa, sb, prec, round_nearest), -1) def mpi_pos(s, prec): sa, sb = s a = mpf_pos(sa, prec, round_floor) b = mpf_pos(sb, prec, round_ceiling) return a, b def mpi_neg(s, prec=0): sa, sb = s a = mpf_neg(sb, prec, round_floor) b = mpf_neg(sa, prec, round_ceiling) return a, b def mpi_abs(s, prec=0): sa, sb = s sas = mpf_sign(sa) sbs = mpf_sign(sb) # Both points nonnegative? if sas >= 0: a = mpf_pos(sa, prec, round_floor) b = mpf_pos(sb, prec, round_ceiling) # Upper point nonnegative? elif sbs >= 0: a = fzero negsa = mpf_neg(sa) if mpf_lt(negsa, sb): b = mpf_pos(sb, prec, round_ceiling) else: b = mpf_pos(negsa, prec, round_ceiling) # Both negative? else: a = mpf_neg(sb, prec, round_floor) b = mpf_neg(sa, prec, round_ceiling) return a, b # TODO: optimize def mpi_mul_mpf(s, t, prec): return mpi_mul(s, (t, t), prec) def mpi_div_mpf(s, t, prec): return mpi_div(s, (t, t), prec) def mpi_mul(s, t, prec=0): sa, sb = s ta, tb = t sas = mpf_sign(sa) sbs = mpf_sign(sb) tas = mpf_sign(ta) tbs = mpf_sign(tb) if sas == sbs == 0: # Should maybe be undefined if ta == fninf or tb == finf: return fninf, finf return fzero, fzero if tas == tbs == 0: # Should maybe be undefined if sa == fninf or sb == finf: return fninf, finf return fzero, fzero if sas >= 0: # positive * positive if tas >= 0: a = mpf_mul(sa, ta, prec, round_floor) b = mpf_mul(sb, tb, prec, round_ceiling) if a == fnan: a = fzero if b == fnan: b = finf # positive * negative elif tbs <= 0: a = mpf_mul(sb, ta, prec, round_floor) b = mpf_mul(sa, tb, prec, round_ceiling) if a == fnan: a = fninf if b == fnan: b = fzero # positive * both signs else: a = mpf_mul(sb, ta, prec, round_floor) b = mpf_mul(sb, tb, prec, round_ceiling) if a == fnan: a = fninf if b == fnan: b = finf elif sbs <= 0: # negative * positive if tas >= 0: a = mpf_mul(sa, tb, prec, round_floor) b = mpf_mul(sb, ta, prec, round_ceiling) if a == fnan: a = fninf if b == fnan: b = fzero # negative * negative elif tbs <= 0: a = mpf_mul(sb, tb, prec, round_floor) b = mpf_mul(sa, ta, prec, round_ceiling) if a == fnan: a = fzero if b == fnan: b = finf # negative * both signs else: a = mpf_mul(sa, tb, prec, round_floor) b = mpf_mul(sa, ta, prec, round_ceiling) if a == fnan: a = fninf if b == fnan: b = finf else: # General case: perform all cross-multiplications and compare # Since the multiplications can be done exactly, we need only # do 4 (instead of 8: two for each rounding mode) cases = [mpf_mul(sa, ta), mpf_mul(sa, tb), mpf_mul(sb, ta), mpf_mul(sb, tb)] if fnan in cases: a, b = (fninf, finf) else: a, b = mpf_min_max(cases) a = mpf_pos(a, prec, round_floor) b = mpf_pos(b, prec, round_ceiling) return a, b def mpi_square(s, prec=0): sa, sb = s if mpf_ge(sa, fzero): a = mpf_mul(sa, sa, prec, round_floor) b = mpf_mul(sb, sb, prec, round_ceiling) elif mpf_le(sb, fzero): a = mpf_mul(sb, sb, prec, round_floor) b = mpf_mul(sa, sa, prec, round_ceiling) else: sa = mpf_neg(sa) sa, sb = mpf_min_max([sa, sb]) a = fzero b = mpf_mul(sb, sb, prec, round_ceiling) return a, b def mpi_div(s, t, prec): sa, sb = s ta, tb = t sas = mpf_sign(sa) sbs = mpf_sign(sb) tas = mpf_sign(ta) tbs = mpf_sign(tb) # 0 / X if sas == sbs == 0: # 0 / <interval containing 0> if (tas < 0 and tbs > 0) or (tas == 0 or tbs == 0): return fninf, finf return fzero, fzero # Denominator contains both negative and positive numbers; # this should properly be a multi-interval, but the closest # match is the entire (extended) real line if tas < 0 and tbs > 0: return fninf, finf # Assume denominator to be nonnegative if tas < 0: return mpi_div(mpi_neg(s), mpi_neg(t), prec) # Division by zero # XXX: make sure all results make sense if tas == 0: # Numerator contains both signs? if sas < 0 and sbs > 0: return fninf, finf if tas == tbs: return fninf, finf # Numerator positive? if sas >= 0: a = mpf_div(sa, tb, prec, round_floor) b = finf if sbs <= 0: a = fninf b = mpf_div(sb, tb, prec, round_ceiling) # Division with positive denominator # We still have to handle nans resulting from inf/0 or inf/inf else: # Nonnegative numerator if sas >= 0: a = mpf_div(sa, tb, prec, round_floor) b = mpf_div(sb, ta, prec, round_ceiling) if a == fnan: a = fzero if b == fnan: b = finf # Nonpositive numerator elif sbs <= 0: a = mpf_div(sa, ta, prec, round_floor) b = mpf_div(sb, tb, prec, round_ceiling) if a == fnan: a = fninf if b == fnan: b = fzero # Numerator contains both signs? else: a = mpf_div(sa, ta, prec, round_floor) b = mpf_div(sb, ta, prec, round_ceiling) if a == fnan: a = fninf if b == fnan: b = finf return a, b def mpi_pi(prec): a = mpf_pi(prec, round_floor) b = mpf_pi(prec, round_ceiling) return a, b def mpi_exp(s, prec): sa, sb = s # exp is monotonic a = mpf_exp(sa, prec, round_floor) b = mpf_exp(sb, prec, round_ceiling) return a, b def mpi_log(s, prec): sa, sb = s # log is monotonic a = mpf_log(sa, prec, round_floor) b = mpf_log(sb, prec, round_ceiling) return a, b def mpi_sqrt(s, prec): sa, sb = s # sqrt is monotonic a = mpf_sqrt(sa, prec, round_floor) b = mpf_sqrt(sb, prec, round_ceiling) return a, b def mpi_atan(s, prec): sa, sb = s a = mpf_atan(sa, prec, round_floor) b = mpf_atan(sb, prec, round_ceiling) return a, b def mpi_pow_int(s, n, prec): sa, sb = s if n < 0: return mpi_div((fone, fone), mpi_pow_int(s, -n, prec+20), prec) if n == 0: return (fone, fone) if n == 1: return s if n == 2: return mpi_square(s, prec) # Odd -- signs are preserved if n & 1: a = mpf_pow_int(sa, n, prec, round_floor) b = mpf_pow_int(sb, n, prec, round_ceiling) # Even -- important to ensure positivity else: sas = mpf_sign(sa) sbs = mpf_sign(sb) # Nonnegative? if sas >= 0: a = mpf_pow_int(sa, n, prec, round_floor) b = mpf_pow_int(sb, n, prec, round_ceiling) # Nonpositive? elif sbs <= 0: a = mpf_pow_int(sb, n, prec, round_floor) b = mpf_pow_int(sa, n, prec, round_ceiling) # Mixed signs? else: a = fzero # max(-a,b)**n sa = mpf_neg(sa) if mpf_ge(sa, sb): b = mpf_pow_int(sa, n, prec, round_ceiling) else: b = mpf_pow_int(sb, n, prec, round_ceiling) return a, b def mpi_pow(s, t, prec): ta, tb = t if ta == tb and ta not in (finf, fninf): if ta == from_int(to_int(ta)): return mpi_pow_int(s, to_int(ta), prec) if ta == fhalf: return mpi_sqrt(s, prec) u = mpi_log(s, prec + 20) v = mpi_mul(u, t, prec + 20) return mpi_exp(v, prec) def MIN(x, y): if mpf_le(x, y): return x return y def MAX(x, y): if mpf_ge(x, y): return x return y def cos_sin_quadrant(x, wp): sign, man, exp, bc = x if x == fzero: return fone, fzero, 0 # TODO: combine evaluation code to avoid duplicate modulo c, s = mpf_cos_sin(x, wp) t, n, wp_ = mod_pi2(man, exp, exp+bc, 15) if sign: n = -1-n return c, s, n def mpi_cos_sin(x, prec): a, b = x if a == b == fzero: return (fone, fone), (fzero, fzero) # Guaranteed to contain both -1 and 1 if (finf in x) or (fninf in x): return (fnone, fone), (fnone, fone) wp = prec + 20 ca, sa, na = cos_sin_quadrant(a, wp) cb, sb, nb = cos_sin_quadrant(b, wp) ca, cb = mpf_min_max([ca, cb]) sa, sb = mpf_min_max([sa, sb]) # Both functions are monotonic within one quadrant if na == nb: pass # Guaranteed to contain both -1 and 1 elif nb - na >= 4: return (fnone, fone), (fnone, fone) else: # cos has maximum between a and b if na//4 != nb//4: cb = fone # cos has minimum if (na-2)//4 != (nb-2)//4: ca = fnone # sin has maximum if (na-1)//4 != (nb-1)//4: sb = fone # sin has minimum if (na-3)//4 != (nb-3)//4: sa = fnone # Perturb to force interval rounding more = from_man_exp((MPZ_ONE<<wp) + (MPZ_ONE<<10), -wp) less = from_man_exp((MPZ_ONE<<wp) - (MPZ_ONE<<10), -wp) def finalize(v, rounding): if bool(v[0]) == (rounding == round_floor): p = more else: p = less v = mpf_mul(v, p, prec, rounding) sign, man, exp, bc = v if exp+bc >= 1: if sign: return fnone return fone return v ca = finalize(ca, round_floor) cb = finalize(cb, round_ceiling) sa = finalize(sa, round_floor) sb = finalize(sb, round_ceiling) return (ca,cb), (sa,sb) def mpi_cos(x, prec): return mpi_cos_sin(x, prec)[0] def mpi_sin(x, prec): return mpi_cos_sin(x, prec)[1] def mpi_tan(x, prec): cos, sin = mpi_cos_sin(x, prec+20) return mpi_div(sin, cos, prec) def mpi_cot(x, prec): cos, sin = mpi_cos_sin(x, prec+20) return mpi_div(cos, sin, prec) def mpi_from_str_a_b(x, y, percent, prec): wp = prec + 20 xa = from_str(x, wp, round_floor) xb = from_str(x, wp, round_ceiling) #ya = from_str(y, wp, round_floor) y = from_str(y, wp, round_ceiling) assert mpf_ge(y, fzero) if percent: y = mpf_mul(MAX(mpf_abs(xa), mpf_abs(xb)), y, wp, round_ceiling) y = mpf_div(y, from_int(100), wp, round_ceiling) a = mpf_sub(xa, y, prec, round_floor) b = mpf_add(xb, y, prec, round_ceiling) return a, b def mpi_from_str(s, prec): """ Parse an interval number given as a string. Allowed forms are "-1.23e-27" Any single decimal floating-point literal. "a +- b" or "a (b)" a is the midpoint of the interval and b is the half-width "a +- b%" or "a (b%)" a is the midpoint of the interval and the half-width is b percent of a (`a \times b / 100`). "[a, b]" The interval indicated directly. "x[y,z]e" x are shared digits, y and z are unequal digits, e is the exponent. """ e = ValueError("Improperly formed interval number '%s'" % s) s = s.replace(" ", "") wp = prec + 20 if "+-" in s: x, y = s.split("+-") return mpi_from_str_a_b(x, y, False, prec) # case 2 elif "(" in s: # Don't confuse with a complex number (x,y) if s[0] == "(" or ")" not in s: raise e s = s.replace(")", "") percent = False if "%" in s: if s[-1] != "%": raise e percent = True s = s.replace("%", "") x, y = s.split("(") return mpi_from_str_a_b(x, y, percent, prec) elif "," in s: if ('[' not in s) or (']' not in s): raise e if s[0] == '[': # case 3 s = s.replace("[", "") s = s.replace("]", "") a, b = s.split(",") a = from_str(a, prec, round_floor) b = from_str(b, prec, round_ceiling) return a, b else: # case 4 x, y = s.split('[') y, z = y.split(',') if 'e' in s: z, e = z.split(']') else: z, e = z.rstrip(']'), '' a = from_str(x+y+e, prec, round_floor) b = from_str(x+z+e, prec, round_ceiling) return a, b else: a = from_str(s, prec, round_floor) b = from_str(s, prec, round_ceiling) return a, b def mpi_to_str(x, dps, use_spaces=True, brackets='[]', mode='brackets', error_dps=4, **kwargs): """ Convert a mpi interval to a string. **Arguments** *dps* decimal places to use for printing *use_spaces* use spaces for more readable output, defaults to true *brackets* pair of strings (or two-character string) giving left and right brackets *mode* mode of display: 'plusminus', 'percent', 'brackets' (default) or 'diff' *error_dps* limit the error to *error_dps* digits (mode 'plusminus and 'percent') Additional keyword arguments are forwarded to the mpf-to-string conversion for the components of the output. **Examples** >>> from mpmath import mpi, mp >>> mp.dps = 30 >>> x = mpi(1, 2)._mpi_ >>> mpi_to_str(x, 2, mode='plusminus') '1.5 +- 0.5' >>> mpi_to_str(x, 2, mode='percent') '1.5 (33.33%)' >>> mpi_to_str(x, 2, mode='brackets') '[1.0, 2.0]' >>> mpi_to_str(x, 2, mode='brackets' , brackets=('<', '>')) '<1.0, 2.0>' >>> x = mpi('5.2582327113062393041', '5.2582327113062749951')._mpi_ >>> mpi_to_str(x, 15, mode='diff') '5.2582327113062[4, 7]' >>> mpi_to_str(mpi(0)._mpi_, 2, mode='percent') '0.0 (0.0%)' """ prec = dps_to_prec(dps) wp = prec + 20 a, b = x mid = mpi_mid(x, prec) delta = mpi_delta(x, prec) a_str = to_str(a, dps, **kwargs) b_str = to_str(b, dps, **kwargs) mid_str = to_str(mid, dps, **kwargs) sp = "" if use_spaces: sp = " " br1, br2 = brackets if mode == 'plusminus': delta_str = to_str(mpf_shift(delta,-1), dps, **kwargs) s = mid_str + sp + "+-" + sp + delta_str elif mode == 'percent': if mid == fzero: p = fzero else: # p = 100 * delta(x) / (2*mid(x)) p = mpf_mul(delta, from_int(100)) p = mpf_div(p, mpf_mul(mid, from_int(2)), wp) s = mid_str + sp + "(" + to_str(p, error_dps) + "%)" elif mode == 'brackets': s = br1 + a_str + "," + sp + b_str + br2 elif mode == 'diff': # use more digits if str(x.a) and str(x.b) are equal if a_str == b_str: a_str = to_str(a, dps+3, **kwargs) b_str = to_str(b, dps+3, **kwargs) # separate mantissa and exponent a = a_str.split('e') if len(a) == 1: a.append('') b = b_str.split('e') if len(b) == 1: b.append('') if a[1] == b[1]: if a[0] != b[0]: for i in xrange(len(a[0]) + 1): if a[0][i] != b[0][i]: break s = (a[0][:i] + br1 + a[0][i:] + ',' + sp + b[0][i:] + br2 + 'e'*min(len(a[1]), 1) + a[1]) else: # no difference s = a[0] + br1 + br2 + 'e'*min(len(a[1]), 1) + a[1] else: s = br1 + 'e'.join(a) + ',' + sp + 'e'.join(b) + br2 else: raise ValueError("'%s' is unknown mode for printing mpi" % mode) return s def mpci_add(x, y, prec): a, b = x c, d = y return mpi_add(a, c, prec), mpi_add(b, d, prec) def mpci_sub(x, y, prec): a, b = x c, d = y return mpi_sub(a, c, prec), mpi_sub(b, d, prec) def mpci_neg(x, prec=0): a, b = x return mpi_neg(a, prec), mpi_neg(b, prec) def mpci_pos(x, prec): a, b = x return mpi_pos(a, prec), mpi_pos(b, prec) def mpci_mul(x, y, prec): # TODO: optimize for real/imag cases a, b = x c, d = y r1 = mpi_mul(a,c) r2 = mpi_mul(b,d) re = mpi_sub(r1,r2,prec) i1 = mpi_mul(a,d) i2 = mpi_mul(b,c) im = mpi_add(i1,i2,prec) return re, im def mpci_div(x, y, prec): # TODO: optimize for real/imag cases a, b = x c, d = y wp = prec+20 m1 = mpi_square(c) m2 = mpi_square(d) m = mpi_add(m1,m2,wp) re = mpi_add(mpi_mul(a,c), mpi_mul(b,d), wp) im = mpi_sub(mpi_mul(b,c), mpi_mul(a,d), wp) re = mpi_div(re, m, prec) im = mpi_div(im, m, prec) return re, im def mpci_exp(x, prec): a, b = x wp = prec+20 r = mpi_exp(a, wp) c, s = mpi_cos_sin(b, wp) a = mpi_mul(r, c, prec) b = mpi_mul(r, s, prec) return a, b def mpi_shift(x, n): a, b = x return mpf_shift(a,n), mpf_shift(b,n) def mpi_cosh_sinh(x, prec): # TODO: accuracy for small x wp = prec+20 e1 = mpi_exp(x, wp) e2 = mpi_div(mpi_one, e1, wp) c = mpi_add(e1, e2, prec) s = mpi_sub(e1, e2, prec) c = mpi_shift(c, -1) s = mpi_shift(s, -1) return c, s def mpci_cos(x, prec): a, b = x wp = prec+10 c, s = mpi_cos_sin(a, wp) ch, sh = mpi_cosh_sinh(b, wp) re = mpi_mul(c, ch, prec) im = mpi_mul(s, sh, prec) return re, mpi_neg(im) def mpci_sin(x, prec): a, b = x wp = prec+10 c, s = mpi_cos_sin(a, wp) ch, sh = mpi_cosh_sinh(b, wp) re = mpi_mul(s, ch, prec) im = mpi_mul(c, sh, prec) return re, im def mpci_abs(x, prec): a, b = x if a == mpi_zero: return mpi_abs(b) if b == mpi_zero: return mpi_abs(a) # Important: nonnegative a = mpi_square(a) b = mpi_square(b) t = mpi_add(a, b, prec+20) return mpi_sqrt(t, prec) def mpi_atan2(y, x, prec): ya, yb = y xa, xb = x # Constrained to the real line if ya == yb == fzero: if mpf_ge(xa, fzero): return mpi_zero return mpi_pi(prec) # Right half-plane if mpf_ge(xa, fzero): if mpf_ge(ya, fzero): a = mpf_atan2(ya, xb, prec, round_floor) else: a = mpf_atan2(ya, xa, prec, round_floor) if mpf_ge(yb, fzero): b = mpf_atan2(yb, xa, prec, round_ceiling) else: b = mpf_atan2(yb, xb, prec, round_ceiling) # Upper half-plane elif mpf_ge(ya, fzero): b = mpf_atan2(ya, xa, prec, round_ceiling) if mpf_le(xb, fzero): a = mpf_atan2(yb, xb, prec, round_floor) else: a = mpf_atan2(ya, xb, prec, round_floor) # Lower half-plane elif mpf_le(yb, fzero): a = mpf_atan2(yb, xa, prec, round_floor) if mpf_le(xb, fzero): b = mpf_atan2(ya, xb, prec, round_ceiling) else: b = mpf_atan2(yb, xb, prec, round_ceiling) # Covering the origin else: b = mpf_pi(prec, round_ceiling) a = mpf_neg(b) return a, b def mpci_arg(z, prec): x, y = z return mpi_atan2(y, x, prec) def mpci_log(z, prec): x, y = z re = mpi_log(mpci_abs(z, prec+20), prec) im = mpci_arg(z, prec) return re, im def mpci_pow(x, y, prec): # TODO: recognize/speed up real cases, integer y yre, yim = y if yim == mpi_zero: ya, yb = yre if ya == yb: sign, man, exp, bc = yb if man and exp >= 0: return mpci_pow_int(x, (-1)**sign * int(man<<exp), prec) # x^0 if yb == fzero: return mpci_pow_int(x, 0, prec) wp = prec+20 return mpci_exp(mpci_mul(y, mpci_log(x, wp), wp), prec) def mpci_square(x, prec): a, b = x # (a+bi)^2 = (a^2-b^2) + 2abi re = mpi_sub(mpi_square(a), mpi_square(b), prec) im = mpi_mul(a, b, prec) im = mpi_shift(im, 1) return re, im def mpci_pow_int(x, n, prec): if n < 0: return mpci_div((mpi_one,mpi_zero), mpci_pow_int(x, -n, prec+20), prec) if n == 0: return mpi_one, mpi_zero if n == 1: return mpci_pos(x, prec) if n == 2: return mpci_square(x, prec) wp = prec + 20 result = (mpi_one, mpi_zero) while n: if n & 1: result = mpci_mul(result, x, wp) n -= 1 x = mpci_square(x, wp) n >>= 1 return mpci_pos(result, prec) gamma_min_a = from_float(1.46163214496) gamma_min_b = from_float(1.46163214497) gamma_min = (gamma_min_a, gamma_min_b) gamma_mono_imag_a = from_float(-1.1) gamma_mono_imag_b = from_float(1.1) def mpi_overlap(x, y): a, b = x c, d = y if mpf_lt(d, a): return False if mpf_gt(c, b): return False return True # type = 0 -- gamma # type = 1 -- factorial # type = 2 -- 1/gamma # type = 3 -- log-gamma def mpi_gamma(z, prec, type=0): a, b = z wp = prec+20 if type == 1: return mpi_gamma(mpi_add(z, mpi_one, wp), prec, 0) # increasing if mpf_gt(a, gamma_min_b): if type == 0: c = mpf_gamma(a, prec, round_floor) d = mpf_gamma(b, prec, round_ceiling) elif type == 2: c = mpf_rgamma(b, prec, round_floor) d = mpf_rgamma(a, prec, round_ceiling) elif type == 3: c = mpf_loggamma(a, prec, round_floor) d = mpf_loggamma(b, prec, round_ceiling) # decreasing elif mpf_gt(a, fzero) and mpf_lt(b, gamma_min_a): if type == 0: c = mpf_gamma(b, prec, round_floor) d = mpf_gamma(a, prec, round_ceiling) elif type == 2: c = mpf_rgamma(a, prec, round_floor) d = mpf_rgamma(b, prec, round_ceiling) elif type == 3: c = mpf_loggamma(b, prec, round_floor) d = mpf_loggamma(a, prec, round_ceiling) else: # TODO: reflection formula znew = mpi_add(z, mpi_one, wp) if type == 0: return mpi_div(mpi_gamma(znew, prec+2, 0), z, prec) if type == 2: return mpi_mul(mpi_gamma(znew, prec+2, 2), z, prec) if type == 3: return mpi_sub(mpi_gamma(znew, prec+2, 3), mpi_log(z, prec+2), prec) return c, d def mpci_gamma(z, prec, type=0): (a1,a2), (b1,b2) = z # Real case if b1 == b2 == fzero and (type != 3 or mpf_gt(a1,fzero)): return mpi_gamma(z, prec, type), mpi_zero # Estimate precision wp = prec+20 if type != 3: amag = a2[2]+a2[3] bmag = b2[2]+b2[3] if a2 != fzero: mag = max(amag, bmag) else: mag = bmag an = abs(to_int(a2)) bn = abs(to_int(b2)) absn = max(an, bn) gamma_size = max(0,absn*mag) wp += bitcount(gamma_size) # Assume type != 1 if type == 1: (a1,a2) = mpi_add((a1,a2), mpi_one, wp); z = (a1,a2), (b1,b2) type = 0 # Avoid non-monotonic region near the negative real axis if mpf_lt(a1, gamma_min_b): if mpi_overlap((b1,b2), (gamma_mono_imag_a, gamma_mono_imag_b)): # TODO: reflection formula #if mpf_lt(a2, mpf_shift(fone,-1)): # znew = mpci_sub((mpi_one,mpi_zero),z,wp) # ... # Recurrence: # gamma(z) = gamma(z+1)/z znew = mpi_add((a1,a2), mpi_one, wp), (b1,b2) if type == 0: return mpci_div(mpci_gamma(znew, prec+2, 0), z, prec) if type == 2: return mpci_mul(mpci_gamma(znew, prec+2, 2), z, prec) if type == 3: return mpci_sub(mpci_gamma(znew, prec+2, 3), mpci_log(z,prec+2), prec) # Use monotonicity (except for a small region close to the # origin and near poles) # upper half-plane if mpf_ge(b1, fzero): minre = mpc_loggamma((a1,b2), wp, round_floor) maxre = mpc_loggamma((a2,b1), wp, round_ceiling) minim = mpc_loggamma((a1,b1), wp, round_floor) maxim = mpc_loggamma((a2,b2), wp, round_ceiling) # lower half-plane elif mpf_le(b2, fzero): minre = mpc_loggamma((a1,b1), wp, round_floor) maxre = mpc_loggamma((a2,b2), wp, round_ceiling) minim = mpc_loggamma((a2,b1), wp, round_floor) maxim = mpc_loggamma((a1,b2), wp, round_ceiling) # crosses real axis else: maxre = mpc_loggamma((a2,fzero), wp, round_ceiling) # stretches more into the lower half-plane if mpf_gt(mpf_neg(b1), b2): minre = mpc_loggamma((a1,b1), wp, round_ceiling) else: minre = mpc_loggamma((a1,b2), wp, round_ceiling) minim = mpc_loggamma((a2,b1), wp, round_floor) maxim = mpc_loggamma((a2,b2), wp, round_floor) w = (minre[0], maxre[0]), (minim[1], maxim[1]) if type == 3: return mpi_pos(w[0], prec), mpi_pos(w[1], prec) if type == 2: w = mpci_neg(w) return mpci_exp(w, prec) def mpi_loggamma(z, prec): return mpi_gamma(z, prec, type=3) def mpci_loggamma(z, prec): return mpci_gamma(z, prec, type=3) def mpi_rgamma(z, prec): return mpi_gamma(z, prec, type=2) def mpci_rgamma(z, prec): return mpci_gamma(z, prec, type=2) def mpi_factorial(z, prec): return mpi_gamma(z, prec, type=1) def mpci_factorial(z, prec): return mpci_gamma(z, prec, type=1)
27,622
28.511752
96
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/libmpc.py
""" Low-level functions for complex arithmetic. """ import sys from .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_TWO, BACKEND from .libmpf import (\ round_floor, round_ceiling, round_down, round_up, round_nearest, round_fast, bitcount, bctable, normalize, normalize1, reciprocal_rnd, rshift, lshift, giant_steps, negative_rnd, to_str, to_fixed, from_man_exp, from_float, to_float, from_int, to_int, fzero, fone, ftwo, fhalf, finf, fninf, fnan, fnone, mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_div, mpf_mul_int, mpf_shift, mpf_sqrt, mpf_hypot, mpf_rdiv_int, mpf_floor, mpf_ceil, mpf_nint, mpf_frac, mpf_sign, mpf_hash, ComplexResult ) from .libelefun import (\ mpf_pi, mpf_exp, mpf_log, mpf_cos_sin, mpf_cosh_sinh, mpf_tan, mpf_pow_int, mpf_log_hypot, mpf_cos_sin_pi, mpf_phi, mpf_cos, mpf_sin, mpf_cos_pi, mpf_sin_pi, mpf_atan, mpf_atan2, mpf_cosh, mpf_sinh, mpf_tanh, mpf_asin, mpf_acos, mpf_acosh, mpf_nthroot, mpf_fibonacci ) # An mpc value is a (real, imag) tuple mpc_one = fone, fzero mpc_zero = fzero, fzero mpc_two = ftwo, fzero mpc_half = (fhalf, fzero) _infs = (finf, fninf) _infs_nan = (finf, fninf, fnan) def mpc_is_inf(z): """Check if either real or imaginary part is infinite""" re, im = z if re in _infs: return True if im in _infs: return True return False def mpc_is_infnan(z): """Check if either real or imaginary part is infinite or nan""" re, im = z if re in _infs_nan: return True if im in _infs_nan: return True return False def mpc_to_str(z, dps, **kwargs): re, im = z rs = to_str(re, dps) if im[0]: return rs + " - " + to_str(mpf_neg(im), dps, **kwargs) + "j" else: return rs + " + " + to_str(im, dps, **kwargs) + "j" def mpc_to_complex(z, strict=False, rnd=round_fast): re, im = z return complex(to_float(re, strict, rnd), to_float(im, strict, rnd)) def mpc_hash(z): if sys.version >= "3.2": re, im = z h = mpf_hash(re) + sys.hash_info.imag * mpf_hash(im) # Need to reduce either module 2^32 or 2^64 h = h % (2**sys.hash_info.width) return int(h) else: try: return hash(mpc_to_complex(z, strict=True)) except OverflowError: return hash(z) def mpc_conjugate(z, prec, rnd=round_fast): re, im = z return re, mpf_neg(im, prec, rnd) def mpc_is_nonzero(z): return z != mpc_zero def mpc_add(z, w, prec, rnd=round_fast): a, b = z c, d = w return mpf_add(a, c, prec, rnd), mpf_add(b, d, prec, rnd) def mpc_add_mpf(z, x, prec, rnd=round_fast): a, b = z return mpf_add(a, x, prec, rnd), b def mpc_sub(z, w, prec=0, rnd=round_fast): a, b = z c, d = w return mpf_sub(a, c, prec, rnd), mpf_sub(b, d, prec, rnd) def mpc_sub_mpf(z, p, prec=0, rnd=round_fast): a, b = z return mpf_sub(a, p, prec, rnd), b def mpc_pos(z, prec, rnd=round_fast): a, b = z return mpf_pos(a, prec, rnd), mpf_pos(b, prec, rnd) def mpc_neg(z, prec=None, rnd=round_fast): a, b = z return mpf_neg(a, prec, rnd), mpf_neg(b, prec, rnd) def mpc_shift(z, n): a, b = z return mpf_shift(a, n), mpf_shift(b, n) def mpc_abs(z, prec, rnd=round_fast): """Absolute value of a complex number, |a+bi|. Returns an mpf value.""" a, b = z return mpf_hypot(a, b, prec, rnd) def mpc_arg(z, prec, rnd=round_fast): """Argument of a complex number. Returns an mpf value.""" a, b = z return mpf_atan2(b, a, prec, rnd) def mpc_floor(z, prec, rnd=round_fast): a, b = z return mpf_floor(a, prec, rnd), mpf_floor(b, prec, rnd) def mpc_ceil(z, prec, rnd=round_fast): a, b = z return mpf_ceil(a, prec, rnd), mpf_ceil(b, prec, rnd) def mpc_nint(z, prec, rnd=round_fast): a, b = z return mpf_nint(a, prec, rnd), mpf_nint(b, prec, rnd) def mpc_frac(z, prec, rnd=round_fast): a, b = z return mpf_frac(a, prec, rnd), mpf_frac(b, prec, rnd) def mpc_mul(z, w, prec, rnd=round_fast): """ Complex multiplication. Returns the real and imaginary part of (a+bi)*(c+di), rounded to the specified precision. The rounding mode applies to the real and imaginary parts separately. """ a, b = z c, d = w p = mpf_mul(a, c) q = mpf_mul(b, d) r = mpf_mul(a, d) s = mpf_mul(b, c) re = mpf_sub(p, q, prec, rnd) im = mpf_add(r, s, prec, rnd) return re, im def mpc_square(z, prec, rnd=round_fast): # (a+b*I)**2 == a**2 - b**2 + 2*I*a*b a, b = z p = mpf_mul(a,a) q = mpf_mul(b,b) r = mpf_mul(a,b, prec, rnd) re = mpf_sub(p, q, prec, rnd) im = mpf_shift(r, 1) return re, im def mpc_mul_mpf(z, p, prec, rnd=round_fast): a, b = z re = mpf_mul(a, p, prec, rnd) im = mpf_mul(b, p, prec, rnd) return re, im def mpc_mul_imag_mpf(z, x, prec, rnd=round_fast): """ Multiply the mpc value z by I*x where x is an mpf value. """ a, b = z re = mpf_neg(mpf_mul(b, x, prec, rnd)) im = mpf_mul(a, x, prec, rnd) return re, im def mpc_mul_int(z, n, prec, rnd=round_fast): a, b = z re = mpf_mul_int(a, n, prec, rnd) im = mpf_mul_int(b, n, prec, rnd) return re, im def mpc_div(z, w, prec, rnd=round_fast): a, b = z c, d = w wp = prec + 10 # mag = c*c + d*d mag = mpf_add(mpf_mul(c, c), mpf_mul(d, d), wp) # (a*c+b*d)/mag, (b*c-a*d)/mag t = mpf_add(mpf_mul(a,c), mpf_mul(b,d), wp) u = mpf_sub(mpf_mul(b,c), mpf_mul(a,d), wp) return mpf_div(t,mag,prec,rnd), mpf_div(u,mag,prec,rnd) def mpc_div_mpf(z, p, prec, rnd=round_fast): """Calculate z/p where p is real""" a, b = z re = mpf_div(a, p, prec, rnd) im = mpf_div(b, p, prec, rnd) return re, im def mpc_reciprocal(z, prec, rnd=round_fast): """Calculate 1/z efficiently""" a, b = z m = mpf_add(mpf_mul(a,a),mpf_mul(b,b),prec+10) re = mpf_div(a, m, prec, rnd) im = mpf_neg(mpf_div(b, m, prec, rnd)) return re, im def mpc_mpf_div(p, z, prec, rnd=round_fast): """Calculate p/z where p is real efficiently""" a, b = z m = mpf_add(mpf_mul(a,a),mpf_mul(b,b), prec+10) re = mpf_div(mpf_mul(a,p), m, prec, rnd) im = mpf_div(mpf_neg(mpf_mul(b,p)), m, prec, rnd) return re, im def complex_int_pow(a, b, n): """Complex integer power: computes (a+b*I)**n exactly for nonnegative n (a and b must be Python ints).""" wre = 1 wim = 0 while n: if n & 1: wre, wim = wre*a - wim*b, wim*a + wre*b n -= 1 a, b = a*a - b*b, 2*a*b n //= 2 return wre, wim def mpc_pow(z, w, prec, rnd=round_fast): if w[1] == fzero: return mpc_pow_mpf(z, w[0], prec, rnd) return mpc_exp(mpc_mul(mpc_log(z, prec+10), w, prec+10), prec, rnd) def mpc_pow_mpf(z, p, prec, rnd=round_fast): psign, pman, pexp, pbc = p if pexp >= 0: return mpc_pow_int(z, (-1)**psign * (pman<<pexp), prec, rnd) if pexp == -1: sqrtz = mpc_sqrt(z, prec+10) return mpc_pow_int(sqrtz, (-1)**psign * pman, prec, rnd) return mpc_exp(mpc_mul_mpf(mpc_log(z, prec+10), p, prec+10), prec, rnd) def mpc_pow_int(z, n, prec, rnd=round_fast): a, b = z if b == fzero: return mpf_pow_int(a, n, prec, rnd), fzero if a == fzero: v = mpf_pow_int(b, n, prec, rnd) n %= 4 if n == 0: return v, fzero elif n == 1: return fzero, v elif n == 2: return mpf_neg(v), fzero elif n == 3: return fzero, mpf_neg(v) if n == 0: return mpc_one if n == 1: return mpc_pos(z, prec, rnd) if n == 2: return mpc_square(z, prec, rnd) if n == -1: return mpc_reciprocal(z, prec, rnd) if n < 0: return mpc_reciprocal(mpc_pow_int(z, -n, prec+4), prec, rnd) asign, aman, aexp, abc = a bsign, bman, bexp, bbc = b if asign: aman = -aman if bsign: bman = -bman de = aexp - bexp abs_de = abs(de) exact_size = n*(abs_de + max(abc, bbc)) if exact_size < 10000: if de > 0: aman <<= de aexp = bexp else: bman <<= (-de) bexp = aexp re, im = complex_int_pow(aman, bman, n) re = from_man_exp(re, int(n*aexp), prec, rnd) im = from_man_exp(im, int(n*bexp), prec, rnd) return re, im return mpc_exp(mpc_mul_int(mpc_log(z, prec+10), n, prec+10), prec, rnd) def mpc_sqrt(z, prec, rnd=round_fast): """Complex square root (principal branch). We have sqrt(a+bi) = sqrt((r+a)/2) + b/sqrt(2*(r+a))*i where r = abs(a+bi), when a+bi is not a negative real number.""" a, b = z if b == fzero: if a == fzero: return (a, b) # When a+bi is a negative real number, we get a real sqrt times i if a[0]: im = mpf_sqrt(mpf_neg(a), prec, rnd) return (fzero, im) else: re = mpf_sqrt(a, prec, rnd) return (re, fzero) wp = prec+20 if not a[0]: # case a positive t = mpf_add(mpc_abs((a, b), wp), a, wp) # t = abs(a+bi) + a u = mpf_shift(t, -1) # u = t/2 re = mpf_sqrt(u, prec, rnd) # re = sqrt(u) v = mpf_shift(t, 1) # v = 2*t w = mpf_sqrt(v, wp) # w = sqrt(v) im = mpf_div(b, w, prec, rnd) # im = b / w else: # case a negative t = mpf_sub(mpc_abs((a, b), wp), a, wp) # t = abs(a+bi) - a u = mpf_shift(t, -1) # u = t/2 im = mpf_sqrt(u, prec, rnd) # im = sqrt(u) v = mpf_shift(t, 1) # v = 2*t w = mpf_sqrt(v, wp) # w = sqrt(v) re = mpf_div(b, w, prec, rnd) # re = b/w if b[0]: re = mpf_neg(re) im = mpf_neg(im) return re, im def mpc_nthroot_fixed(a, b, n, prec): # a, b signed integers at fixed precision prec start = 50 a1 = int(rshift(a, prec - n*start)) b1 = int(rshift(b, prec - n*start)) try: r = (a1 + 1j * b1)**(1.0/n) re = r.real im = r.imag re = MPZ(int(re)) im = MPZ(int(im)) except OverflowError: a1 = from_int(a1, start) b1 = from_int(b1, start) fn = from_int(n) nth = mpf_rdiv_int(1, fn, start) re, im = mpc_pow((a1, b1), (nth, fzero), start) re = to_int(re) im = to_int(im) extra = 10 prevp = start extra1 = n for p in giant_steps(start, prec+extra): # this is slow for large n, unlike int_pow_fixed re2, im2 = complex_int_pow(re, im, n-1) re2 = rshift(re2, (n-1)*prevp - p - extra1) im2 = rshift(im2, (n-1)*prevp - p - extra1) r4 = (re2*re2 + im2*im2) >> (p + extra1) ap = rshift(a, prec - p) bp = rshift(b, prec - p) rec = (ap * re2 + bp * im2) >> p imc = (-ap * im2 + bp * re2) >> p reb = (rec << p) // r4 imb = (imc << p) // r4 re = (reb + (n-1)*lshift(re, p-prevp))//n im = (imb + (n-1)*lshift(im, p-prevp))//n prevp = p return re, im def mpc_nthroot(z, n, prec, rnd=round_fast): """ Complex n-th root. Use Newton method as in the real case when it is faster, otherwise use z**(1/n) """ a, b = z if a[0] == 0 and b == fzero: re = mpf_nthroot(a, n, prec, rnd) return (re, fzero) if n < 2: if n == 0: return mpc_one if n == 1: return mpc_pos((a, b), prec, rnd) if n == -1: return mpc_div(mpc_one, (a, b), prec, rnd) inverse = mpc_nthroot((a, b), -n, prec+5, reciprocal_rnd[rnd]) return mpc_div(mpc_one, inverse, prec, rnd) if n <= 20: prec2 = int(1.2 * (prec + 10)) asign, aman, aexp, abc = a bsign, bman, bexp, bbc = b pf = mpc_abs((a,b), prec) if pf[-2] + pf[-1] > -10 and pf[-2] + pf[-1] < prec: af = to_fixed(a, prec2) bf = to_fixed(b, prec2) re, im = mpc_nthroot_fixed(af, bf, n, prec2) extra = 10 re = from_man_exp(re, -prec2-extra, prec2, rnd) im = from_man_exp(im, -prec2-extra, prec2, rnd) return re, im fn = from_int(n) prec2 = prec+10 + 10 nth = mpf_rdiv_int(1, fn, prec2) re, im = mpc_pow((a, b), (nth, fzero), prec2, rnd) re = normalize(re[0], re[1], re[2], re[3], prec, rnd) im = normalize(im[0], im[1], im[2], im[3], prec, rnd) return re, im def mpc_cbrt(z, prec, rnd=round_fast): """ Complex cubic root. """ return mpc_nthroot(z, 3, prec, rnd) def mpc_exp(z, prec, rnd=round_fast): """ Complex exponential function. We use the direct formula exp(a+bi) = exp(a) * (cos(b) + sin(b)*i) for the computation. This formula is very nice because it is pefectly stable; since we just do real multiplications, the only numerical errors that can creep in are single-ulp rounding errors. The formula is efficient since mpmath's real exp is quite fast and since we can compute cos and sin simultaneously. It is no problem if a and b are large; if the implementations of exp/cos/sin are accurate and efficient for all real numbers, then so is this function for all complex numbers. """ a, b = z if a == fzero: return mpf_cos_sin(b, prec, rnd) if b == fzero: return mpf_exp(a, prec, rnd), fzero mag = mpf_exp(a, prec+4, rnd) c, s = mpf_cos_sin(b, prec+4, rnd) re = mpf_mul(mag, c, prec, rnd) im = mpf_mul(mag, s, prec, rnd) return re, im def mpc_log(z, prec, rnd=round_fast): re = mpf_log_hypot(z[0], z[1], prec, rnd) im = mpc_arg(z, prec, rnd) return re, im def mpc_cos(z, prec, rnd=round_fast): """Complex cosine. The formula used is cos(a+bi) = cos(a)*cosh(b) - sin(a)*sinh(b)*i. The same comments apply as for the complex exp: only real multiplications are pewrormed, so no cancellation errors are possible. The formula is also efficient since we can compute both pairs (cos, sin) and (cosh, sinh) in single stwps.""" a, b = z if b == fzero: return mpf_cos(a, prec, rnd), fzero if a == fzero: return mpf_cosh(b, prec, rnd), fzero wp = prec + 6 c, s = mpf_cos_sin(a, wp) ch, sh = mpf_cosh_sinh(b, wp) re = mpf_mul(c, ch, prec, rnd) im = mpf_mul(s, sh, prec, rnd) return re, mpf_neg(im) def mpc_sin(z, prec, rnd=round_fast): """Complex sine. We have sin(a+bi) = sin(a)*cosh(b) + cos(a)*sinh(b)*i. See the docstring for mpc_cos for additional comments.""" a, b = z if b == fzero: return mpf_sin(a, prec, rnd), fzero if a == fzero: return fzero, mpf_sinh(b, prec, rnd) wp = prec + 6 c, s = mpf_cos_sin(a, wp) ch, sh = mpf_cosh_sinh(b, wp) re = mpf_mul(s, ch, prec, rnd) im = mpf_mul(c, sh, prec, rnd) return re, im def mpc_tan(z, prec, rnd=round_fast): """Complex tangent. Computed as tan(a+bi) = sin(2a)/M + sinh(2b)/M*i where M = cos(2a) + cosh(2b).""" a, b = z asign, aman, aexp, abc = a bsign, bman, bexp, bbc = b if b == fzero: return mpf_tan(a, prec, rnd), fzero if a == fzero: return fzero, mpf_tanh(b, prec, rnd) wp = prec + 15 a = mpf_shift(a, 1) b = mpf_shift(b, 1) c, s = mpf_cos_sin(a, wp) ch, sh = mpf_cosh_sinh(b, wp) # TODO: handle cancellation when c ~= -1 and ch ~= 1 mag = mpf_add(c, ch, wp) re = mpf_div(s, mag, prec, rnd) im = mpf_div(sh, mag, prec, rnd) return re, im def mpc_cos_pi(z, prec, rnd=round_fast): a, b = z if b == fzero: return mpf_cos_pi(a, prec, rnd), fzero b = mpf_mul(b, mpf_pi(prec+5), prec+5) if a == fzero: return mpf_cosh(b, prec, rnd), fzero wp = prec + 6 c, s = mpf_cos_sin_pi(a, wp) ch, sh = mpf_cosh_sinh(b, wp) re = mpf_mul(c, ch, prec, rnd) im = mpf_mul(s, sh, prec, rnd) return re, mpf_neg(im) def mpc_sin_pi(z, prec, rnd=round_fast): a, b = z if b == fzero: return mpf_sin_pi(a, prec, rnd), fzero b = mpf_mul(b, mpf_pi(prec+5), prec+5) if a == fzero: return fzero, mpf_sinh(b, prec, rnd) wp = prec + 6 c, s = mpf_cos_sin_pi(a, wp) ch, sh = mpf_cosh_sinh(b, wp) re = mpf_mul(s, ch, prec, rnd) im = mpf_mul(c, sh, prec, rnd) return re, im def mpc_cos_sin(z, prec, rnd=round_fast): a, b = z if a == fzero: ch, sh = mpf_cosh_sinh(b, prec, rnd) return (ch, fzero), (fzero, sh) if b == fzero: c, s = mpf_cos_sin(a, prec, rnd) return (c, fzero), (s, fzero) wp = prec + 6 c, s = mpf_cos_sin(a, wp) ch, sh = mpf_cosh_sinh(b, wp) cre = mpf_mul(c, ch, prec, rnd) cim = mpf_mul(s, sh, prec, rnd) sre = mpf_mul(s, ch, prec, rnd) sim = mpf_mul(c, sh, prec, rnd) return (cre, mpf_neg(cim)), (sre, sim) def mpc_cos_sin_pi(z, prec, rnd=round_fast): a, b = z if b == fzero: c, s = mpf_cos_sin_pi(a, prec, rnd) return (c, fzero), (s, fzero) b = mpf_mul(b, mpf_pi(prec+5), prec+5) if a == fzero: ch, sh = mpf_cosh_sinh(b, prec, rnd) return (ch, fzero), (fzero, sh) wp = prec + 6 c, s = mpf_cos_sin_pi(a, wp) ch, sh = mpf_cosh_sinh(b, wp) cre = mpf_mul(c, ch, prec, rnd) cim = mpf_mul(s, sh, prec, rnd) sre = mpf_mul(s, ch, prec, rnd) sim = mpf_mul(c, sh, prec, rnd) return (cre, mpf_neg(cim)), (sre, sim) def mpc_cosh(z, prec, rnd=round_fast): """Complex hyperbolic cosine. Computed as cosh(z) = cos(z*i).""" a, b = z return mpc_cos((b, mpf_neg(a)), prec, rnd) def mpc_sinh(z, prec, rnd=round_fast): """Complex hyperbolic sine. Computed as sinh(z) = -i*sin(z*i).""" a, b = z b, a = mpc_sin((b, a), prec, rnd) return a, b def mpc_tanh(z, prec, rnd=round_fast): """Complex hyperbolic tangent. Computed as tanh(z) = -i*tan(z*i).""" a, b = z b, a = mpc_tan((b, a), prec, rnd) return a, b # TODO: avoid loss of accuracy def mpc_atan(z, prec, rnd=round_fast): a, b = z # atan(z) = (I/2)*(log(1-I*z) - log(1+I*z)) # x = 1-I*z = 1 + b - I*a # y = 1+I*z = 1 - b + I*a wp = prec + 15 x = mpf_add(fone, b, wp), mpf_neg(a) y = mpf_sub(fone, b, wp), a l1 = mpc_log(x, wp) l2 = mpc_log(y, wp) a, b = mpc_sub(l1, l2, prec, rnd) # (I/2) * (a+b*I) = (-b/2 + a/2*I) v = mpf_neg(mpf_shift(b,-1)), mpf_shift(a,-1) # Subtraction at infinity gives correct real part but # wrong imaginary part (should be zero) if v[1] == fnan and mpc_is_inf(z): v = (v[0], fzero) return v beta_crossover = from_float(0.6417) alpha_crossover = from_float(1.5) def acos_asin(z, prec, rnd, n): """ complex acos for n = 0, asin for n = 1 The algorithm is described in T.E. Hull, T.F. Fairgrieve and P.T.P. Tang 'Implementing the Complex Arcsine and Arcosine Functions using Exception Handling', ACM Trans. on Math. Software Vol. 23 (1997), p299 The complex acos and asin can be defined as acos(z) = acos(beta) - I*sign(a)* log(alpha + sqrt(alpha**2 -1)) asin(z) = asin(beta) + I*sign(a)* log(alpha + sqrt(alpha**2 -1)) where z = a + I*b alpha = (1/2)*(r + s); beta = (1/2)*(r - s) = a/alpha r = sqrt((a+1)**2 + y**2); s = sqrt((a-1)**2 + y**2) These expressions are rewritten in different ways in different regions, delimited by two crossovers alpha_crossover and beta_crossover, and by abs(a) <= 1, in order to improve the numerical accuracy. """ a, b = z wp = prec + 10 # special cases with real argument if b == fzero: am = mpf_sub(fone, mpf_abs(a), wp) # case abs(a) <= 1 if not am[0]: if n == 0: return mpf_acos(a, prec, rnd), fzero else: return mpf_asin(a, prec, rnd), fzero # cases abs(a) > 1 else: # case a < -1 if a[0]: pi = mpf_pi(prec, rnd) c = mpf_acosh(mpf_neg(a), prec, rnd) if n == 0: return pi, mpf_neg(c) else: return mpf_neg(mpf_shift(pi, -1)), c # case a > 1 else: c = mpf_acosh(a, prec, rnd) if n == 0: return fzero, c else: pi = mpf_pi(prec, rnd) return mpf_shift(pi, -1), mpf_neg(c) asign = bsign = 0 if a[0]: a = mpf_neg(a) asign = 1 if b[0]: b = mpf_neg(b) bsign = 1 am = mpf_sub(fone, a, wp) ap = mpf_add(fone, a, wp) r = mpf_hypot(ap, b, wp) s = mpf_hypot(am, b, wp) alpha = mpf_shift(mpf_add(r, s, wp), -1) beta = mpf_div(a, alpha, wp) b2 = mpf_mul(b,b, wp) # case beta <= beta_crossover if not mpf_sub(beta_crossover, beta, wp)[0]: if n == 0: re = mpf_acos(beta, wp) else: re = mpf_asin(beta, wp) else: # to compute the real part in this region use the identity # asin(beta) = atan(beta/sqrt(1-beta**2)) # beta/sqrt(1-beta**2) = (alpha + a) * (alpha - a) # alpha + a is numerically accurate; alpha - a can have # cancellations leading to numerical inaccuracies, so rewrite # it in differente ways according to the region Ax = mpf_add(alpha, a, wp) # case a <= 1 if not am[0]: # c = b*b/(r + (a+1)); d = (s + (1-a)) # alpha - a = (1/2)*(c + d) # case n=0: re = atan(sqrt((1/2) * Ax * (c + d))/a) # case n=1: re = atan(a/sqrt((1/2) * Ax * (c + d))) c = mpf_div(b2, mpf_add(r, ap, wp), wp) d = mpf_add(s, am, wp) re = mpf_shift(mpf_mul(Ax, mpf_add(c, d, wp), wp), -1) if n == 0: re = mpf_atan(mpf_div(mpf_sqrt(re, wp), a, wp), wp) else: re = mpf_atan(mpf_div(a, mpf_sqrt(re, wp), wp), wp) else: # c = Ax/(r + (a+1)); d = Ax/(s - (1-a)) # alpha - a = (1/2)*(c + d) # case n = 0: re = atan(b*sqrt(c + d)/2/a) # case n = 1: re = atan(a/(b*sqrt(c + d)/2) c = mpf_div(Ax, mpf_add(r, ap, wp), wp) d = mpf_div(Ax, mpf_sub(s, am, wp), wp) re = mpf_shift(mpf_add(c, d, wp), -1) re = mpf_mul(b, mpf_sqrt(re, wp), wp) if n == 0: re = mpf_atan(mpf_div(re, a, wp), wp) else: re = mpf_atan(mpf_div(a, re, wp), wp) # to compute alpha + sqrt(alpha**2 - 1), if alpha <= alpha_crossover # replace it with 1 + Am1 + sqrt(Am1*(alpha+1))) # where Am1 = alpha -1 # if alpha <= alpha_crossover: if not mpf_sub(alpha_crossover, alpha, wp)[0]: c1 = mpf_div(b2, mpf_add(r, ap, wp), wp) # case a < 1 if mpf_neg(am)[0]: # Am1 = (1/2) * (b*b/(r + (a+1)) + b*b/(s + (1-a)) c2 = mpf_add(s, am, wp) c2 = mpf_div(b2, c2, wp) Am1 = mpf_shift(mpf_add(c1, c2, wp), -1) else: # Am1 = (1/2) * (b*b/(r + (a+1)) + (s - (1-a))) c2 = mpf_sub(s, am, wp) Am1 = mpf_shift(mpf_add(c1, c2, wp), -1) # im = log(1 + Am1 + sqrt(Am1*(alpha+1))) im = mpf_mul(Am1, mpf_add(alpha, fone, wp), wp) im = mpf_log(mpf_add(fone, mpf_add(Am1, mpf_sqrt(im, wp), wp), wp), wp) else: # im = log(alpha + sqrt(alpha*alpha - 1)) im = mpf_sqrt(mpf_sub(mpf_mul(alpha, alpha, wp), fone, wp), wp) im = mpf_log(mpf_add(alpha, im, wp), wp) if asign: if n == 0: re = mpf_sub(mpf_pi(wp), re, wp) else: re = mpf_neg(re) if not bsign and n == 0: im = mpf_neg(im) if bsign and n == 1: im = mpf_neg(im) re = normalize(re[0], re[1], re[2], re[3], prec, rnd) im = normalize(im[0], im[1], im[2], im[3], prec, rnd) return re, im def mpc_acos(z, prec, rnd=round_fast): return acos_asin(z, prec, rnd, 0) def mpc_asin(z, prec, rnd=round_fast): return acos_asin(z, prec, rnd, 1) def mpc_asinh(z, prec, rnd=round_fast): # asinh(z) = I * asin(-I z) a, b = z a, b = mpc_asin((b, mpf_neg(a)), prec, rnd) return mpf_neg(b), a def mpc_acosh(z, prec, rnd=round_fast): # acosh(z) = -I * acos(z) for Im(acos(z)) <= 0 # +I * acos(z) otherwise a, b = mpc_acos(z, prec, rnd) if b[0] or b == fzero: return mpf_neg(b), a else: return b, mpf_neg(a) def mpc_atanh(z, prec, rnd=round_fast): # atanh(z) = (log(1+z)-log(1-z))/2 wp = prec + 15 a = mpc_add(z, mpc_one, wp) b = mpc_sub(mpc_one, z, wp) a = mpc_log(a, wp) b = mpc_log(b, wp) v = mpc_shift(mpc_sub(a, b, wp), -1) # Subtraction at infinity gives correct imaginary part but # wrong real part (should be zero) if v[0] == fnan and mpc_is_inf(z): v = (fzero, v[1]) return v def mpc_fibonacci(z, prec, rnd=round_fast): re, im = z if im == fzero: return (mpf_fibonacci(re, prec, rnd), fzero) size = max(abs(re[2]+re[3]), abs(re[2]+re[3])) wp = prec + size + 20 a = mpf_phi(wp) b = mpf_add(mpf_shift(a, 1), fnone, wp) u = mpc_pow((a, fzero), z, wp) v = mpc_cos_pi(z, wp) v = mpc_div(v, u, wp) u = mpc_sub(u, v, wp) u = mpc_div_mpf(u, b, prec, rnd) return u def mpf_expj(x, prec, rnd='f'): raise ComplexResult def mpc_expj(z, prec, rnd='f'): re, im = z if im == fzero: return mpf_cos_sin(re, prec, rnd) if re == fzero: return mpf_exp(mpf_neg(im), prec, rnd), fzero ey = mpf_exp(mpf_neg(im), prec+10) c, s = mpf_cos_sin(re, prec+10) re = mpf_mul(ey, c, prec, rnd) im = mpf_mul(ey, s, prec, rnd) return re, im def mpf_expjpi(x, prec, rnd='f'): raise ComplexResult def mpc_expjpi(z, prec, rnd='f'): re, im = z if im == fzero: return mpf_cos_sin_pi(re, prec, rnd) sign, man, exp, bc = im wp = prec+10 if man: wp += max(0, exp+bc) im = mpf_neg(mpf_mul(mpf_pi(wp), im, wp)) if re == fzero: return mpf_exp(im, prec, rnd), fzero ey = mpf_exp(im, prec+10) c, s = mpf_cos_sin_pi(re, prec+10) re = mpf_mul(ey, c, prec, rnd) im = mpf_mul(ey, s, prec, rnd) return re, im if BACKEND == 'sage': try: import sage.libs.mpmath.ext_libmp as _lbmp mpc_exp = _lbmp.mpc_exp mpc_sqrt = _lbmp.mpc_sqrt except (ImportError, AttributeError): print("Warning: Sage imports in libmpc failed")
26,869
31.141148
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/backend.py
import os import sys #----------------------------------------------------------------------------# # Support GMPY for high-speed large integer arithmetic. # # # # To allow an external module to handle arithmetic, we need to make sure # # that all high-precision variables are declared of the correct type. MPZ # # is the constructor for the high-precision type. It defaults to Python's # # long type but can be assinged another type, typically gmpy.mpz. # # # # MPZ must be used for the mantissa component of an mpf and must be used # # for internal fixed-point operations. # # # # Side-effects # # 1) "is" cannot be used to test for special values. Must use "==". # # 2) There are bugs in GMPY prior to v1.02 so we must use v1.03 or later. # #----------------------------------------------------------------------------# # So we can import it from this module gmpy = None sage = None sage_utils = None if sys.version_info[0] < 3: python3 = False else: python3 = True BACKEND = 'python' from .six import exec_, print_ if not python3: MPZ = long xrange = xrange basestring = basestring else: MPZ = int xrange = range basestring = str # Define constants for calculating hash on Python 3.2. if sys.version >= "3.2": HASH_MODULUS = sys.hash_info.modulus if sys.hash_info.width == 32: HASH_BITS = 31 else: HASH_BITS = 61 else: HASH_MODULUS = None HASH_BITS = None if 'MPMATH_NOGMPY' not in os.environ: try: try: import gmpy2 as gmpy except ImportError: try: import gmpy except ImportError: raise ImportError if gmpy.version() >= '1.03': BACKEND = 'gmpy' MPZ = gmpy.mpz except: pass if 'MPMATH_NOSAGE' not in os.environ: try: import sage.all import sage.libs.mpmath.utils as _sage_utils sage = sage.all sage_utils = _sage_utils BACKEND = 'sage' MPZ = sage.Integer except: pass if 'MPMATH_STRICT' in os.environ: STRICT = True else: STRICT = False MPZ_TYPE = type(MPZ(0)) MPZ_ZERO = MPZ(0) MPZ_ONE = MPZ(1) MPZ_TWO = MPZ(2) MPZ_THREE = MPZ(3) MPZ_FIVE = MPZ(5) try: if BACKEND == 'python': int_types = (int, long) else: int_types = (int, long, MPZ_TYPE) except NameError: if BACKEND == 'python': int_types = (int,) else: int_types = (int, MPZ_TYPE)
2,857
27.019608
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/__init__.py
from .libmpf import (prec_to_dps, dps_to_prec, repr_dps, round_down, round_up, round_floor, round_ceiling, round_nearest, to_pickable, from_pickable, ComplexResult, fzero, fnzero, fone, fnone, ftwo, ften, fhalf, fnan, finf, fninf, math_float_inf, round_int, normalize, normalize1, from_man_exp, from_int, to_man_exp, to_int, mpf_ceil, mpf_floor, mpf_nint, mpf_frac, from_float, to_float, from_rational, to_rational, to_fixed, mpf_rand, mpf_eq, mpf_hash, mpf_cmp, mpf_lt, mpf_le, mpf_gt, mpf_ge, mpf_pos, mpf_neg, mpf_abs, mpf_sign, mpf_add, mpf_sub, mpf_sum, mpf_mul, mpf_mul_int, mpf_shift, mpf_frexp, mpf_div, mpf_rdiv_int, mpf_mod, mpf_pow_int, mpf_perturb, to_digits_exp, to_str, str_to_man_exp, from_str, from_bstr, to_bstr, mpf_sqrt, mpf_hypot) from .libmpc import (mpc_one, mpc_zero, mpc_two, mpc_half, mpc_is_inf, mpc_is_infnan, mpc_to_str, mpc_to_complex, mpc_hash, mpc_conjugate, mpc_is_nonzero, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_pos, mpc_neg, mpc_shift, mpc_abs, mpc_arg, mpc_floor, mpc_ceil, mpc_nint, mpc_frac, mpc_mul, mpc_square, mpc_mul_mpf, mpc_mul_imag_mpf, mpc_mul_int, mpc_div, mpc_div_mpf, mpc_reciprocal, mpc_mpf_div, complex_int_pow, mpc_pow, mpc_pow_mpf, mpc_pow_int, mpc_sqrt, mpc_nthroot, mpc_cbrt, mpc_exp, mpc_log, mpc_cos, mpc_sin, mpc_tan, mpc_cos_pi, mpc_sin_pi, mpc_cosh, mpc_sinh, mpc_tanh, mpc_atan, mpc_acos, mpc_asin, mpc_asinh, mpc_acosh, mpc_atanh, mpc_fibonacci, mpf_expj, mpf_expjpi, mpc_expj, mpc_expjpi, mpc_cos_sin, mpc_cos_sin_pi) from .libelefun import (ln2_fixed, mpf_ln2, ln10_fixed, mpf_ln10, pi_fixed, mpf_pi, e_fixed, mpf_e, phi_fixed, mpf_phi, degree_fixed, mpf_degree, mpf_pow, mpf_nthroot, mpf_cbrt, log_int_fixed, agm_fixed, mpf_log, mpf_log_hypot, mpf_exp, mpf_cos_sin, mpf_cos, mpf_sin, mpf_tan, mpf_cos_sin_pi, mpf_cos_pi, mpf_sin_pi, mpf_cosh_sinh, mpf_cosh, mpf_sinh, mpf_tanh, mpf_atan, mpf_atan2, mpf_asin, mpf_acos, mpf_asinh, mpf_acosh, mpf_atanh, mpf_fibonacci) from .libhyper import (NoConvergence, make_hyp_summator, mpf_erf, mpf_erfc, mpf_ei, mpc_ei, mpf_e1, mpc_e1, mpf_expint, mpf_ci_si, mpf_ci, mpf_si, mpc_ci, mpc_si, mpf_besseljn, mpc_besseljn, mpf_agm, mpf_agm1, mpc_agm, mpc_agm1, mpf_ellipk, mpc_ellipk, mpf_ellipe, mpc_ellipe) from .gammazeta import (catalan_fixed, mpf_catalan, khinchin_fixed, mpf_khinchin, glaisher_fixed, mpf_glaisher, apery_fixed, mpf_apery, euler_fixed, mpf_euler, mertens_fixed, mpf_mertens, twinprime_fixed, mpf_twinprime, mpf_bernoulli, bernfrac, mpf_gamma_int, mpf_factorial, mpc_factorial, mpf_gamma, mpc_gamma, mpf_loggamma, mpc_loggamma, mpf_rgamma, mpc_rgamma, mpf_gamma_old, mpc_gamma_old, mpf_factorial_old, mpc_factorial_old, mpf_harmonic, mpc_harmonic, mpf_psi0, mpc_psi0, mpf_psi, mpc_psi, mpf_zeta_int, mpf_zeta, mpc_zeta, mpf_altzeta, mpc_altzeta, mpf_zetasum, mpc_zetasum) from .libmpi import (mpi_str, mpi_from_str, mpi_to_str, mpi_eq, mpi_ne, mpi_lt, mpi_le, mpi_gt, mpi_ge, mpi_add, mpi_sub, mpi_delta, mpi_mid, mpi_pos, mpi_neg, mpi_abs, mpi_mul, mpi_div, mpi_exp, mpi_log, mpi_sqrt, mpi_pow_int, mpi_pow, mpi_cos_sin, mpi_cos, mpi_sin, mpi_tan, mpi_cot, mpi_atan, mpi_atan2, mpci_pos, mpci_neg, mpci_add, mpci_sub, mpci_mul, mpci_div, mpci_pow, mpci_abs, mpci_pow, mpci_exp, mpci_log, mpci_cos, mpci_sin, mpi_gamma, mpci_gamma, mpi_loggamma, mpci_loggamma, mpi_rgamma, mpci_rgamma, mpi_factorial, mpci_factorial) from .libintmath import (trailing, bitcount, numeral, bin_to_radix, isqrt, isqrt_small, isqrt_fast, sqrt_fixed, sqrtrem, ifib, ifac, list_primes, isprime, moebius, gcd, eulernum, stirling1, stirling2) from .backend import (gmpy, sage, BACKEND, STRICT, MPZ, MPZ_TYPE, MPZ_ZERO, MPZ_ONE, MPZ_TWO, MPZ_THREE, MPZ_FIVE, int_types, HASH_MODULUS, HASH_BITS)
3,832
47.518987
74
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpmath/libmp/libintmath.py
""" Utility functions for integer math. TODO: rename, cleanup, perhaps move the gmpy wrapper code here from settings.py """ import math from bisect import bisect from .backend import xrange from .backend import BACKEND, gmpy, sage, sage_utils, MPZ, MPZ_ONE, MPZ_ZERO def giant_steps(start, target, n=2): """ Return a list of integers ~= [start, n*start, ..., target/n^2, target/n, target] but conservatively rounded so that the quotient between two successive elements is actually slightly less than n. With n = 2, this describes suitable precision steps for a quadratically convergent algorithm such as Newton's method; with n = 3 steps for cubic convergence (Halley's method), etc. >>> giant_steps(50,1000) [66, 128, 253, 502, 1000] >>> giant_steps(50,1000,4) [65, 252, 1000] """ L = [target] while L[-1] > start*n: L = L + [L[-1]//n + 2] return L[::-1] def rshift(x, n): """For an integer x, calculate x >> n with the fastest (floor) rounding. Unlike the plain Python expression (x >> n), n is allowed to be negative, in which case a left shift is performed.""" if n >= 0: return x >> n else: return x << (-n) def lshift(x, n): """For an integer x, calculate x << n. Unlike the plain Python expression (x << n), n is allowed to be negative, in which case a right shift with default (floor) rounding is performed.""" if n >= 0: return x << n else: return x >> (-n) if BACKEND == 'sage': import operator rshift = operator.rshift lshift = operator.lshift def python_trailing(n): """Count the number of trailing zero bits in abs(n).""" if not n: return 0 t = 0 while not n & 1: n >>= 1 t += 1 return t if BACKEND == 'gmpy': if gmpy.version() >= '2': def gmpy_trailing(n): """Count the number of trailing zero bits in abs(n) using gmpy.""" if n: return MPZ(n).bit_scan1() else: return 0 else: def gmpy_trailing(n): """Count the number of trailing zero bits in abs(n) using gmpy.""" if n: return MPZ(n).scan1() else: return 0 # Small powers of 2 powers = [1<<_ for _ in range(300)] def python_bitcount(n): """Calculate bit size of the nonnegative integer n.""" bc = bisect(powers, n) if bc != 300: return bc bc = int(math.log(n, 2)) - 4 return bc + bctable[n>>bc] def gmpy_bitcount(n): """Calculate bit size of the nonnegative integer n.""" if n: return MPZ(n).numdigits(2) else: return 0 #def sage_bitcount(n): # if n: return MPZ(n).nbits() # else: return 0 def sage_trailing(n): return MPZ(n).trailing_zero_bits() if BACKEND == 'gmpy': bitcount = gmpy_bitcount trailing = gmpy_trailing elif BACKEND == 'sage': sage_bitcount = sage_utils.bitcount bitcount = sage_bitcount trailing = sage_trailing else: bitcount = python_bitcount trailing = python_trailing if BACKEND == 'gmpy' and 'bit_length' in dir(gmpy): bitcount = gmpy.bit_length # Used to avoid slow function calls as far as possible trailtable = [trailing(n) for n in range(256)] bctable = [bitcount(n) for n in range(1024)] # TODO: speed up for bases 2, 4, 8, 16, ... def bin_to_radix(x, xbits, base, bdigits): """Changes radix of a fixed-point number; i.e., converts x * 2**xbits to floor(x * 10**bdigits).""" return x * (MPZ(base)**bdigits) >> xbits stddigits = '0123456789abcdefghijklmnopqrstuvwxyz' def small_numeral(n, base=10, digits=stddigits): """Return the string numeral of a positive integer in an arbitrary base. Most efficient for small input.""" if base == 10: return str(n) digs = [] while n: n, digit = divmod(n, base) digs.append(digits[digit]) return "".join(digs[::-1]) def numeral_python(n, base=10, size=0, digits=stddigits): """Represent the integer n as a string of digits in the given base. Recursive division is used to make this function about 3x faster than Python's str() for converting integers to decimal strings. The 'size' parameters specifies the number of digits in n; this number is only used to determine splitting points and need not be exact.""" if n <= 0: if not n: return "0" return "-" + numeral(-n, base, size, digits) # Fast enough to do directly if size < 250: return small_numeral(n, base, digits) # Divide in half half = (size // 2) + (size & 1) A, B = divmod(n, base**half) ad = numeral(A, base, half, digits) bd = numeral(B, base, half, digits).rjust(half, "0") return ad + bd def numeral_gmpy(n, base=10, size=0, digits=stddigits): """Represent the integer n as a string of digits in the given base. Recursive division is used to make this function about 3x faster than Python's str() for converting integers to decimal strings. The 'size' parameters specifies the number of digits in n; this number is only used to determine splitting points and need not be exact.""" if n < 0: return "-" + numeral(-n, base, size, digits) # gmpy.digits() may cause a segmentation fault when trying to convert # extremely large values to a string. The size limit may need to be # adjusted on some platforms, but 1500000 works on Windows and Linux. if size < 1500000: return gmpy.digits(n, base) # Divide in half half = (size // 2) + (size & 1) A, B = divmod(n, MPZ(base)**half) ad = numeral(A, base, half, digits) bd = numeral(B, base, half, digits).rjust(half, "0") return ad + bd if BACKEND == "gmpy": numeral = numeral_gmpy else: numeral = numeral_python _1_800 = 1<<800 _1_600 = 1<<600 _1_400 = 1<<400 _1_200 = 1<<200 _1_100 = 1<<100 _1_50 = 1<<50 def isqrt_small_python(x): """ Correctly (floor) rounded integer square root, using division. Fast up to ~200 digits. """ if not x: return x if x < _1_800: # Exact with IEEE double precision arithmetic if x < _1_50: return int(x**0.5) # Initial estimate can be any integer >= the true root; round up r = int(x**0.5 * 1.00000000000001) + 1 else: bc = bitcount(x) n = bc//2 r = int((x>>(2*n-100))**0.5+2)<<(n-50) # +2 is to round up # The following iteration now precisely computes floor(sqrt(x)) # See e.g. Crandall & Pomerance, "Prime Numbers: A Computational # Perspective" while 1: y = (r+x//r)>>1 if y >= r: return r r = y def isqrt_fast_python(x): """ Fast approximate integer square root, computed using division-free Newton iteration for large x. For random integers the result is almost always correct (floor(sqrt(x))), but is 1 ulp too small with a roughly 0.1% probability. If x is very close to an exact square, the answer is 1 ulp wrong with high probability. With 0 guard bits, the largest error over a set of 10^5 random inputs of size 1-10^5 bits was 3 ulp. The use of 10 guard bits almost certainly guarantees a max 1 ulp error. """ # Use direct division-based iteration if sqrt(x) < 2^400 # Assume floating-point square root accurate to within 1 ulp, then: # 0 Newton iterations good to 52 bits # 1 Newton iterations good to 104 bits # 2 Newton iterations good to 208 bits # 3 Newton iterations good to 416 bits if x < _1_800: y = int(x**0.5) if x >= _1_100: y = (y + x//y) >> 1 if x >= _1_200: y = (y + x//y) >> 1 if x >= _1_400: y = (y + x//y) >> 1 return y bc = bitcount(x) guard_bits = 10 x <<= 2*guard_bits bc += 2*guard_bits bc += (bc&1) hbc = bc//2 startprec = min(50, hbc) # Newton iteration for 1/sqrt(x), with floating-point starting value r = int(2.0**(2*startprec) * (x >> (bc-2*startprec)) ** -0.5) pp = startprec for p in giant_steps(startprec, hbc): # r**2, scaled from real size 2**(-bc) to 2**p r2 = (r*r) >> (2*pp - p) # x*r**2, scaled from real size ~1.0 to 2**p xr2 = ((x >> (bc-p)) * r2) >> p # New value of r, scaled from real size 2**(-bc/2) to 2**p r = (r * ((3<<p) - xr2)) >> (pp+1) pp = p # (1/sqrt(x))*x = sqrt(x) return (r*(x>>hbc)) >> (p+guard_bits) def sqrtrem_python(x): """Correctly rounded integer (floor) square root with remainder.""" # to check cutoff: # plot(lambda x: timing(isqrt, 2**int(x)), [0,2000]) if x < _1_600: y = isqrt_small_python(x) return y, x - y*y y = isqrt_fast_python(x) + 1 rem = x - y*y # Correct remainder while rem < 0: y -= 1 rem += (1+2*y) else: if rem: while rem > 2*(1+y): y += 1 rem -= (1+2*y) return y, rem def isqrt_python(x): """Integer square root with correct (floor) rounding.""" return sqrtrem_python(x)[0] def sqrt_fixed(x, prec): return isqrt_fast(x<<prec) sqrt_fixed2 = sqrt_fixed if BACKEND == 'gmpy': if gmpy.version() >= '2': isqrt_small = isqrt_fast = isqrt = gmpy.isqrt sqrtrem = gmpy.isqrt_rem else: isqrt_small = isqrt_fast = isqrt = gmpy.sqrt sqrtrem = gmpy.sqrtrem elif BACKEND == 'sage': isqrt_small = isqrt_fast = isqrt = \ getattr(sage_utils, "isqrt", lambda n: MPZ(n).isqrt()) sqrtrem = lambda n: MPZ(n).sqrtrem() else: isqrt_small = isqrt_small_python isqrt_fast = isqrt_fast_python isqrt = isqrt_python sqrtrem = sqrtrem_python def ifib(n, _cache={}): """Computes the nth Fibonacci number as an integer, for integer n.""" if n < 0: return (-1)**(-n+1) * ifib(-n) if n in _cache: return _cache[n] m = n # Use Dijkstra's logarithmic algorithm # The following implementation is basically equivalent to # http://en.literateprograms.org/Fibonacci_numbers_(Scheme) a, b, p, q = MPZ_ONE, MPZ_ZERO, MPZ_ZERO, MPZ_ONE while n: if n & 1: aq = a*q a, b = b*q+aq+a*p, b*p+aq n -= 1 else: qq = q*q p, q = p*p+qq, qq+2*p*q n >>= 1 if m < 250: _cache[m] = b return b MAX_FACTORIAL_CACHE = 1000 def ifac(n, memo={0:1, 1:1}): """Return n factorial (for integers n >= 0 only).""" f = memo.get(n) if f: return f k = len(memo) p = memo[k-1] MAX = MAX_FACTORIAL_CACHE while k <= n: p *= k if k <= MAX: memo[k] = p k += 1 return p def ifac2(n, memo_pair=[{0:1}, {1:1}]): """Return n!! (double factorial), integers n >= 0 only.""" memo = memo_pair[n&1] f = memo.get(n) if f: return f k = max(memo) p = memo[k] MAX = MAX_FACTORIAL_CACHE while k < n: k += 2 p *= k if k <= MAX: memo[k] = p return p if BACKEND == 'gmpy': ifac = gmpy.fac elif BACKEND == 'sage': ifac = lambda n: int(sage.factorial(n)) ifib = sage.fibonacci def list_primes(n): n = n + 1 sieve = list(xrange(n)) sieve[:2] = [0, 0] for i in xrange(2, int(n**0.5)+1): if sieve[i]: for j in xrange(i**2, n, i): sieve[j] = 0 return [p for p in sieve if p] if BACKEND == 'sage': # Note: it is *VERY* important for performance that we convert # the list to Python ints. def list_primes(n): return [int(_) for _ in sage.primes(n+1)] small_odd_primes = (3,5,7,11,13,17,19,23,29,31,37,41,43,47) small_odd_primes_set = set(small_odd_primes) def isprime(n): """ Determines whether n is a prime number. A probabilistic test is performed if n is very large. No special trick is used for detecting perfect powers. >>> sum(list_primes(100000)) 454396537 >>> sum(n*isprime(n) for n in range(100000)) 454396537 """ n = int(n) if not n & 1: return n == 2 if n < 50: return n in small_odd_primes_set for p in small_odd_primes: if not n % p: return False m = n-1 s = trailing(m) d = m >> s def test(a): x = pow(a,d,n) if x == 1 or x == m: return True for r in xrange(1,s): x = x**2 % n if x == m: return True return False # See http://primes.utm.edu/prove/prove2_3.html if n < 1373653: witnesses = [2,3] elif n < 341550071728321: witnesses = [2,3,5,7,11,13,17] else: witnesses = small_odd_primes for a in witnesses: if not test(a): return False return True def moebius(n): """ Evaluates the Moebius function which is `mu(n) = (-1)^k` if `n` is a product of `k` distinct primes and `mu(n) = 0` otherwise. TODO: speed up using factorization """ n = abs(int(n)) if n < 2: return n factors = [] for p in xrange(2, n+1): if not (n % p): if not (n % p**2): return 0 if not sum(p % f for f in factors): factors.append(p) return (-1)**len(factors) def gcd(*args): a = 0 for b in args: if a: while b: a, b = b, a % b else: a = b return a # Comment by Juan Arias de Reyna: # # I learn this method to compute EulerE[2n] from van de Lune. # # We apply the formula EulerE[2n] = (-1)^n 2**(-2n) sum_{j=0}^n a(2n,2j+1) # # where the numbers a(n,j) vanish for j > n+1 or j <= -1 and satisfies # # a(0,-1) = a(0,0) = 0; a(0,1)= 1; a(0,2) = a(0,3) = 0 # # a(n,j) = a(n-1,j) when n+j is even # a(n,j) = (j-1) a(n-1,j-1) + (j+1) a(n-1,j+1) when n+j is odd # # # But we can use only one array unidimensional a(j) since to compute # a(n,j) we only need to know a(n-1,k) where k and j are of different parity # and we have not to conserve the used values. # # We cached up the values of Euler numbers to sufficiently high order. # # Important Observation: If we pretend to use the numbers # EulerE[1], EulerE[2], ... , EulerE[n] # it is convenient to compute first EulerE[n], since the algorithm # computes first all # the previous ones, and keeps them in the CACHE MAX_EULER_CACHE = 500 def eulernum(m, _cache={0:MPZ_ONE}): r""" Computes the Euler numbers `E(n)`, which can be defined as coefficients of the Taylor expansion of `1/cosh x`: .. math :: \frac{1}{\cosh x} = \sum_{n=0}^\infty \frac{E_n}{n!} x^n Example:: >>> [int(eulernum(n)) for n in range(11)] [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521] >>> [int(eulernum(n)) for n in range(11)] # test cache [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521] """ # for odd m > 1, the Euler numbers are zero if m & 1: return MPZ_ZERO f = _cache.get(m) if f: return f MAX = MAX_EULER_CACHE n = m a = [MPZ(_) for _ in [0,0,1,0,0,0]] for n in range(1, m+1): for j in range(n+1, -1, -2): a[j+1] = (j-1)*a[j] + (j+1)*a[j+2] a.append(0) suma = 0 for k in range(n+1, -1, -2): suma += a[k+1] if n <= MAX: _cache[n] = ((-1)**(n//2))*(suma // 2**n) if n == m: return ((-1)**(n//2))*suma // 2**n def stirling1(n, k): """ Stirling number of the first kind. """ if n < 0 or k < 0: raise ValueError if k >= n: return MPZ(n == k) if k < 1: return MPZ_ZERO L = [MPZ_ZERO] * (k+1) L[1] = MPZ_ONE for m in xrange(2, n+1): for j in xrange(min(k, m), 0, -1): L[j] = (m-1) * L[j] + L[j-1] return (-1)**(n+k) * L[k] def stirling2(n, k): """ Stirling number of the second kind. """ if n < 0 or k < 0: raise ValueError if k >= n: return MPZ(n == k) if k <= 1: return MPZ(k == 1) s = MPZ_ZERO t = MPZ_ONE for j in xrange(k+1): if (k + j) & 1: s -= t * MPZ(j)**n else: s += t * MPZ(j)**n t = t * (k - j) // (j + 1) return s // ifac(k)
16,462
27.532062
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/main.py
""" pasteurize: automatic conversion of Python 3 code to clean 2/3 code =================================================================== ``pasteurize`` attempts to convert existing Python 3 code into source-compatible Python 2 and 3 code. Use it like this on Python 3 code: $ pasteurize --verbose mypython3script.py This removes any Py3-only syntax (e.g. new metaclasses) and adds these import lines: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_hooks() from builtins import * To write changes to the files, use the -w flag. It also adds any other wrappers needed for Py2/3 compatibility. Note that separate stages are not available (or needed) when converting from Python 3 with ``pasteurize`` as they are when converting from Python 2 with ``futurize``. The --all-imports option forces adding all ``__future__`` imports, ``builtins`` imports, and standard library aliases, even if they don't seem necessary for the current state of each module. (This can simplify testing, and can reduce the need to think about Py2 compatibility when editing the code further.) """ from __future__ import (absolute_import, print_function, unicode_literals) import sys import logging import optparse from lib2to3.main import main, warn, StdoutRefactoringTool from lib2to3 import refactor from future import __version__ from libpasteurize.fixes import fix_names def main(args=None): """Main program. Returns a suggested exit status (0, 1, 2). """ # Set up option parser parser = optparse.OptionParser(usage="pasteurize [options] file|dir ...") parser.add_option("-V", "--version", action="store_true", help="Report the version number of pasteurize") parser.add_option("-a", "--all-imports", action="store_true", help="Adds all __future__ and future imports to each module") parser.add_option("-f", "--fix", action="append", default=[], help="Each FIX specifies a transformation; default: all") parser.add_option("-j", "--processes", action="store", default=1, type="int", help="Run 2to3 concurrently") parser.add_option("-x", "--nofix", action="append", default=[], help="Prevent a fixer from being run.") parser.add_option("-l", "--list-fixes", action="store_true", help="List available transformations") # parser.add_option("-p", "--print-function", action="store_true", # help="Modify the grammar so that print() is a function") parser.add_option("-v", "--verbose", action="store_true", help="More verbose logging") parser.add_option("--no-diffs", action="store_true", help="Don't show diffs of the refactoring") parser.add_option("-w", "--write", action="store_true", help="Write back modified files") parser.add_option("-n", "--nobackups", action="store_true", default=False, help="Don't write backups for modified files.") # Parse command line arguments refactor_stdin = False flags = {} options, args = parser.parse_args(args) fixer_pkg = 'libpasteurize.fixes' avail_fixes = fix_names flags["print_function"] = True if not options.write and options.no_diffs: warn("not writing files and not printing diffs; that's not very useful") if not options.write and options.nobackups: parser.error("Can't use -n without -w") if options.version: print(__version__) return 0 if options.list_fixes: print("Available transformations for the -f/--fix option:") for fixname in sorted(avail_fixes): print(fixname) if not args: return 0 if not args: print("At least one file or directory argument required.", file=sys.stderr) print("Use --help to show usage.", file=sys.stderr) return 2 if "-" in args: refactor_stdin = True if options.write: print("Can't write to stdin.", file=sys.stderr) return 2 # Set up logging handler level = logging.DEBUG if options.verbose else logging.INFO logging.basicConfig(format='%(name)s: %(message)s', level=level) # Initialize the refactoring tool unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix) extra_fixes = set() if options.all_imports: prefix = 'libpasteurize.fixes.' extra_fixes.add(prefix + 'fix_add_all__future__imports') extra_fixes.add(prefix + 'fix_add_future_standard_library_import') extra_fixes.add(prefix + 'fix_add_all_future_builtins') fixer_names = avail_fixes | extra_fixes - unwanted_fixes rt = StdoutRefactoringTool(sorted(fixer_names), flags, set(), options.nobackups, not options.no_diffs) # Refactor all files and directories passed as arguments if not rt.errors: if refactor_stdin: rt.refactor_stdin() else: try: rt.refactor(args, options.write, None, options.processes) except refactor.MultiprocessingUnsupported: assert options.processes > 1 print("Sorry, -j isn't " \ "supported on this platform.", file=sys.stderr) return 1 rt.summarize() # Return error status (0 if rt.errors is zero) return int(bool(rt.errors))
5,705
37.04
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/__init__.py
# empty to make this a package
31
15
30
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_raise.py
u"""Fixer for 'raise E(V).with_traceback(T)' -> 'raise E, V, T'""" from lib2to3 import fixer_base from lib2to3.fixer_util import Comma, Node, Leaf, token, syms class FixRaise(fixer_base.BaseFix): PATTERN = u""" raise_stmt< 'raise' (power< name=any [trailer< '(' val=any* ')' >] [trailer< '.' 'with_traceback' > trailer< '(' trc=any ')' >] > | any) ['from' chain=any] >""" def transform(self, node, results): name, val, trc = (results.get(u"name"), results.get(u"val"), results.get(u"trc")) chain = results.get(u"chain") if chain is not None: self.warning(node, u"explicit exception chaining is not supported in Python 2") chain.prev_sibling.remove() chain.remove() if trc is not None: val = val[0] if val else Leaf(token.NAME, u"None") val.prefix = trc.prefix = u" " kids = [Leaf(token.NAME, u"raise"), name.clone(), Comma(), val.clone(), Comma(), trc.clone()] raise_stmt = Node(syms.raise_stmt, kids) node.replace(raise_stmt)
1,099
41.307692
101
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_metaclass.py
u""" Fixer for (metaclass=X) -> __metaclass__ = X Some semantics (see PEP 3115) may be altered in the translation.""" from lib2to3 import fixer_base from lib2to3.fixer_util import Name, syms, Node, Leaf, Newline, find_root from lib2to3.pygram import token from libfuturize.fixer_util import indentation, suitify # from ..fixer_util import Name, syms, Node, Leaf, Newline, find_root, indentation, suitify def has_metaclass(parent): results = None for node in parent.children: kids = node.children if node.type == syms.argument: if kids[0] == Leaf(token.NAME, u"metaclass") and \ kids[1] == Leaf(token.EQUAL, u"=") and \ kids[2]: #Hack to avoid "class X(=):" with this case. results = [node] + kids break elif node.type == syms.arglist: # Argument list... loop through it looking for: # Node(*, [*, Leaf(token.NAME, u"metaclass"), Leaf(token.EQUAL, u"="), Leaf(*, *)] for child in node.children: if results: break if child.type == token.COMMA: #Store the last comma, which precedes the metaclass comma = child elif type(child) == Node: meta = equal = name = None for arg in child.children: if arg == Leaf(token.NAME, u"metaclass"): #We have the (metaclass) part meta = arg elif meta and arg == Leaf(token.EQUAL, u"="): #We have the (metaclass=) part equal = arg elif meta and equal: #Here we go, we have (metaclass=X) name = arg results = (comma, meta, equal, name) break return results class FixMetaclass(fixer_base.BaseFix): PATTERN = u""" classdef<any*> """ def transform(self, node, results): meta_results = has_metaclass(node) if not meta_results: return for meta in meta_results: meta.remove() target = Leaf(token.NAME, u"__metaclass__") equal = Leaf(token.EQUAL, u"=", prefix=u" ") # meta is the last item in what was returned by has_metaclass(): name name = meta name.prefix = u" " stmt_node = Node(syms.atom, [target, equal, name]) suitify(node) for item in node.children: if item.type == syms.suite: for stmt in item.children: if stmt.type == token.INDENT: # Insert, in reverse order, the statement, a newline, # and an indent right after the first indented line loc = item.children.index(stmt) + 1 # Keep consistent indentation form ident = Leaf(token.INDENT, stmt.value) item.insert_child(loc, ident) item.insert_child(loc, Newline()) item.insert_child(loc, stmt_node) break
3,268
40.379747
94
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_memoryview.py
u""" Fixer for memoryview(s) -> buffer(s). Explicit because some memoryview methods are invalid on buffer objects. """ from lib2to3 import fixer_base from lib2to3.fixer_util import Name class FixMemoryview(fixer_base.BaseFix): explicit = True # User must specify that they want this. PATTERN = u""" power< name='memoryview' trailer< '(' [any] ')' > rest=any* > """ def transform(self, node, results): name = results[u"name"] name.replace(Name(u"buffer", prefix=name.prefix))
551
24.090909
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_division.py
u""" Fixer for division: from __future__ import division if needed """ from lib2to3 import fixer_base from libfuturize.fixer_util import token, future_import def match_division(node): u""" __future__.division redefines the meaning of a single slash for division, so we match that and only that. """ slash = token.SLASH return node.type == slash and not node.next_sibling.type == slash and \ not node.prev_sibling.type == slash class FixDivision(fixer_base.BaseFix): run_order = 4 # this seems to be ignored? def match(self, node): u""" Since the tree needs to be fixed once and only once if and only if it matches, then we can start discarding matches after we make the first. """ return match_division(node) def transform(self, node, results): future_import(u"division", node)
904
30.206897
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_annotations.py
u""" Fixer to remove function annotations """ from lib2to3 import fixer_base from lib2to3.pgen2 import token from lib2to3.fixer_util import syms warning_text = u"Removing function annotations completely." def param_without_annotations(node): return node.children[0] class FixAnnotations(fixer_base.BaseFix): warned = False def warn_once(self, node, reason): if not self.warned: self.warned = True self.warning(node, reason=reason) PATTERN = u""" funcdef< 'def' any parameters< '(' [params=any] ')' > ['->' ret=any] ':' any* > """ def transform(self, node, results): u""" This just strips annotations from the funcdef completely. """ params = results.get(u"params") ret = results.get(u"ret") if ret is not None: assert ret.prev_sibling.type == token.RARROW, u"Invalid return annotation" self.warn_once(node, reason=warning_text) ret.prev_sibling.remove() ret.remove() if params is None: return if params.type == syms.typedargslist: # more than one param in a typedargslist for param in params.children: if param.type == syms.tname: self.warn_once(node, reason=warning_text) param.replace(param_without_annotations(param)) elif params.type == syms.tname: # one param self.warn_once(node, reason=warning_text) params.replace(param_without_annotations(params))
1,585
31.367347
93
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_kwargs.py
u""" Fixer for Python 3 function parameter syntax This fixer is rather sensitive to incorrect py3k syntax. """ # Note: "relevant" parameters are parameters following the first STAR in the list. from lib2to3 import fixer_base from lib2to3.fixer_util import token, String, Newline, Comma, Name from libfuturize.fixer_util import indentation, suitify, DoubleStar _assign_template = u"%(name)s = %(kwargs)s['%(name)s']; del %(kwargs)s['%(name)s']" _if_template = u"if '%(name)s' in %(kwargs)s: %(assign)s" _else_template = u"else: %(name)s = %(default)s" _kwargs_default_name = u"_3to2kwargs" def gen_params(raw_params): u""" Generator that yields tuples of (name, default_value) for each parameter in the list If no default is given, then it is default_value is None (not Leaf(token.NAME, 'None')) """ assert raw_params[0].type == token.STAR and len(raw_params) > 2 curr_idx = 2 # the first place a keyword-only parameter name can be is index 2 max_idx = len(raw_params) while curr_idx < max_idx: curr_item = raw_params[curr_idx] prev_item = curr_item.prev_sibling if curr_item.type != token.NAME: curr_idx += 1 continue if prev_item is not None and prev_item.type == token.DOUBLESTAR: break name = curr_item.value nxt = curr_item.next_sibling if nxt is not None and nxt.type == token.EQUAL: default_value = nxt.next_sibling curr_idx += 2 else: default_value = None yield (name, default_value) curr_idx += 1 def remove_params(raw_params, kwargs_default=_kwargs_default_name): u""" Removes all keyword-only args from the params list and a bare star, if any. Does not add the kwargs dict if needed. Returns True if more action is needed, False if not (more action is needed if no kwargs dict exists) """ assert raw_params[0].type == token.STAR if raw_params[1].type == token.COMMA: raw_params[0].remove() raw_params[1].remove() kw_params = raw_params[2:] else: kw_params = raw_params[3:] for param in kw_params: if param.type != token.DOUBLESTAR: param.remove() else: return False else: return True def needs_fixing(raw_params, kwargs_default=_kwargs_default_name): u""" Returns string with the name of the kwargs dict if the params after the first star need fixing Otherwise returns empty string """ found_kwargs = False needs_fix = False for t in raw_params[2:]: if t.type == token.COMMA: # Commas are irrelevant at this stage. continue elif t.type == token.NAME and not found_kwargs: # Keyword-only argument: definitely need to fix. needs_fix = True elif t.type == token.NAME and found_kwargs: # Return 'foobar' of **foobar, if needed. return t.value if needs_fix else u'' elif t.type == token.DOUBLESTAR: # Found either '*' from **foobar. found_kwargs = True else: # Never found **foobar. Return a synthetic name, if needed. return kwargs_default if needs_fix else u'' class FixKwargs(fixer_base.BaseFix): run_order = 7 # Run after function annotations are removed PATTERN = u"funcdef< 'def' NAME parameters< '(' arglist=typedargslist< params=any* > ')' > ':' suite=any >" def transform(self, node, results): params_rawlist = results[u"params"] for i, item in enumerate(params_rawlist): if item.type == token.STAR: params_rawlist = params_rawlist[i:] break else: return # params is guaranteed to be a list starting with *. # if fixing is needed, there will be at least 3 items in this list: # [STAR, COMMA, NAME] is the minimum that we need to worry about. new_kwargs = needs_fixing(params_rawlist) # new_kwargs is the name of the kwargs dictionary. if not new_kwargs: return suitify(node) # At this point, params_rawlist is guaranteed to be a list # beginning with a star that includes at least one keyword-only param # e.g., [STAR, NAME, COMMA, NAME, COMMA, DOUBLESTAR, NAME] or # [STAR, COMMA, NAME], or [STAR, COMMA, NAME, COMMA, DOUBLESTAR, NAME] # Anatomy of a funcdef: ['def', 'name', parameters, ':', suite] # Anatomy of that suite: [NEWLINE, INDENT, first_stmt, all_other_stmts] # We need to insert our new stuff before the first_stmt and change the # first_stmt's prefix. suite = node.children[4] first_stmt = suite.children[2] ident = indentation(first_stmt) for name, default_value in gen_params(params_rawlist): if default_value is None: suite.insert_child(2, Newline()) suite.insert_child(2, String(_assign_template %{u'name':name, u'kwargs':new_kwargs}, prefix=ident)) else: suite.insert_child(2, Newline()) suite.insert_child(2, String(_else_template %{u'name':name, u'default':default_value}, prefix=ident)) suite.insert_child(2, Newline()) suite.insert_child(2, String(_if_template %{u'assign':_assign_template %{u'name':name, u'kwargs':new_kwargs}, u'name':name, u'kwargs':new_kwargs}, prefix=ident)) first_stmt.prefix = ident suite.children[2].prefix = u"" # Now, we need to fix up the list of params. must_add_kwargs = remove_params(params_rawlist) if must_add_kwargs: arglist = results[u'arglist'] if len(arglist.children) > 0 and arglist.children[-1].type != token.COMMA: arglist.append_child(Comma()) arglist.append_child(DoubleStar(prefix=u" ")) arglist.append_child(Name(new_kwargs))
6,008
39.328859
177
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_printfunction.py
u""" Fixer for print: from __future__ import print_function. """ from lib2to3 import fixer_base from libfuturize.fixer_util import future_import class FixPrintfunction(fixer_base.BaseFix): # explicit = True PATTERN = u""" power< 'print' trailer < '(' any* ')' > any* > """ def transform(self, node, results): future_import(u"print_function", node)
401
21.333333
60
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_future_builtins.py
""" Adds this import line: from builtins import XYZ for each of the functions XYZ that is used in the module. """ from __future__ import unicode_literals from lib2to3 import fixer_base from lib2to3.pygram import python_symbols as syms from lib2to3.fixer_util import Name, Call, in_special_context from libfuturize.fixer_util import touch_import_top # All builtins are: # from future.builtins.iterators import (filter, map, zip) # from future.builtins.misc import (ascii, chr, hex, input, isinstance, oct, open, round, super) # from future.types import (bytes, dict, int, range, str) # We don't need isinstance any more. replaced_builtins = '''filter map zip ascii chr hex input next oct open round super bytes dict int range str'''.split() expression = '|'.join(["name='{0}'".format(name) for name in replaced_builtins]) class FixFutureBuiltins(fixer_base.BaseFix): BM_compatible = True run_order = 9 # Currently we only match uses as a function. This doesn't match e.g.: # if isinstance(s, str): # ... PATTERN = """ power< ({0}) trailer< '(' args=[any] ')' > rest=any* > """.format(expression) def transform(self, node, results): name = results["name"] touch_import_top(u'builtins', name.value, node) # name.replace(Name(u"input", prefix=name.prefix))
1,451
29.25
100
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_newstyle.py
u""" Fixer for "class Foo: ..." -> "class Foo(object): ..." """ from lib2to3 import fixer_base from lib2to3.fixer_util import LParen, RParen, Name from libfuturize.fixer_util import touch_import_top def insert_object(node, idx): node.insert_child(idx, RParen()) node.insert_child(idx, Name(u"object")) node.insert_child(idx, LParen()) class FixNewstyle(fixer_base.BaseFix): # Match: # class Blah: # and: # class Blah(): PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >" def transform(self, node, results): colon = results[u"colon"] idx = node.children.index(colon) if (node.children[idx-2].value == '(' and node.children[idx-1].value == ')'): del node.children[idx-2:idx] idx -= 2 insert_object(node, idx) touch_import_top(u'builtins', 'object', node)
888
25.147059
65
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_getcwd.py
u""" Fixer for os.getcwd() -> os.getcwdu(). Also warns about "from os import getcwd", suggesting the above form. """ from lib2to3 import fixer_base from lib2to3.fixer_util import Name class FixGetcwd(fixer_base.BaseFix): PATTERN = u""" power< 'os' trailer< dot='.' name='getcwd' > any* > | import_from< 'from' 'os' 'import' bad='getcwd' > """ def transform(self, node, results): if u"name" in results: name = results[u"name"] name.replace(Name(u"getcwdu", prefix=name.prefix)) elif u"bad" in results: # Can't convert to getcwdu and then expect to catch every use. self.cannot_convert(node, u"import os, use os.getcwd() instead.") return else: raise ValueError(u"For some reason, the pattern matcher failed.")
873
31.37037
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_throw.py
u"""Fixer for 'g.throw(E(V).with_traceback(T))' -> 'g.throw(E, V, T)'""" from lib2to3 import fixer_base from lib2to3.pytree import Node, Leaf from lib2to3.pgen2 import token from lib2to3.fixer_util import Comma class FixThrow(fixer_base.BaseFix): PATTERN = u""" power< any trailer< '.' 'throw' > trailer< '(' args=power< exc=any trailer< '(' val=any* ')' > trailer< '.' 'with_traceback' > trailer< '(' trc=any ')' > > ')' > > """ def transform(self, node, results): syms = self.syms exc, val, trc = (results[u"exc"], results[u"val"], results[u"trc"]) val = val[0] if val else Leaf(token.NAME, u"None") val.prefix = trc.prefix = u" " kids = [exc.clone(), Comma(), val.clone(), Comma(), trc.clone()] args = results[u"args"] args.children = kids
835
33.833333
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_add_all__future__imports.py
""" Fixer for adding: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals This is done when converting from Py3 to both Py3/Py2. """ from lib2to3 import fixer_base from libfuturize.fixer_util import future_import class FixAddAllFutureImports(fixer_base.BaseFix): BM_compatible = True PATTERN = "file_input" run_order = 1 def transform(self, node, results): future_import(u"unicode_literals", node) future_import(u"print_function", node) future_import(u"division", node) future_import(u"absolute_import", node)
677
25.076923
54
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_fullargspec.py
u""" Fixer for getfullargspec -> getargspec """ from lib2to3 import fixer_base from lib2to3.fixer_util import Name warn_msg = u"some of the values returned by getfullargspec are not valid in Python 2 and have no equivalent." class FixFullargspec(fixer_base.BaseFix): PATTERN = u"'getfullargspec'" def transform(self, node, results): self.warning(node, warn_msg) return Name(u"getargspec", prefix=node.prefix)
442
25.058824
109
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_add_future_standard_library_import.py
""" For the ``future`` package. Adds this import line: from future import standard_library after any __future__ imports but before any other imports. Doesn't actually change the imports to Py3 style. """ from lib2to3 import fixer_base from libfuturize.fixer_util import touch_import_top class FixAddFutureStandardLibraryImport(fixer_base.BaseFix): BM_compatible = True PATTERN = "file_input" run_order = 8 def transform(self, node, results): # TODO: add a blank line between any __future__ imports and this? touch_import_top(u'future', u'standard_library', node) # TODO: also add standard_library.install_hooks()
663
26.666667
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_raise_.py
u"""Fixer for raise E(V).with_traceback(T) to: from future.utils import raise_ ... raise_(E, V, T) TODO: FIXME!! """ from lib2to3 import fixer_base from lib2to3.fixer_util import Comma, Node, Leaf, token, syms class FixRaise(fixer_base.BaseFix): PATTERN = u""" raise_stmt< 'raise' (power< name=any [trailer< '(' val=any* ')' >] [trailer< '.' 'with_traceback' > trailer< '(' trc=any ')' >] > | any) ['from' chain=any] >""" def transform(self, node, results): FIXME name, val, trc = (results.get(u"name"), results.get(u"val"), results.get(u"trc")) chain = results.get(u"chain") if chain is not None: self.warning(node, u"explicit exception chaining is not supported in Python 2") chain.prev_sibling.remove() chain.remove() if trc is not None: val = val[0] if val else Leaf(token.NAME, u"None") val.prefix = trc.prefix = u" " kids = [Leaf(token.NAME, u"raise"), name.clone(), Comma(), val.clone(), Comma(), trc.clone()] raise_stmt = Node(syms.raise_stmt, kids) node.replace(raise_stmt)
1,225
33.055556
101
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/feature_base.py
u""" Base classes for features that are backwards-incompatible. Usage: features = Features() features.add(Feature("py3k_feature", "power< 'py3k' any* >", "2.7")) PATTERN = features.PATTERN """ pattern_unformatted = u"%s=%s" # name=pattern, for dict lookups message_unformatted = u""" %s is only supported in Python %s and above.""" class Feature(object): u""" A feature has a name, a pattern, and a minimum version of Python 2.x required to use the feature (or 3.x if there is no backwards-compatible version of 2.x) """ def __init__(self, name, PATTERN, version): self.name = name self._pattern = PATTERN self.version = version def message_text(self): u""" Format the above text with the name and minimum version required. """ return message_unformatted % (self.name, self.version) class Features(set): u""" A set of features that generates a pattern for the features it contains. This set will act like a mapping in that we map names to patterns. """ mapping = {} def update_mapping(self): u""" Called every time we care about the mapping of names to features. """ self.mapping = dict([(f.name, f) for f in iter(self)]) @property def PATTERN(self): u""" Uses the mapping of names to features to return a PATTERN suitable for using the lib2to3 patcomp. """ self.update_mapping() return u" |\n".join([pattern_unformatted % (f.name, f._pattern) for f in iter(self)]) def __getitem__(self, key): u""" Implement a simple mapping to get patterns from names. """ return self.mapping[key]
1,727
28.793103
93
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_unpacking.py
u""" Fixer for: (a,)* *b (,c)* [,] = s for (a,)* *b (,c)* [,] in d: ... """ from lib2to3 import fixer_base from itertools import count from lib2to3.fixer_util import (Assign, Comma, Call, Newline, Name, Number, token, syms, Node, Leaf) from libfuturize.fixer_util import indentation, suitify, commatize # from libfuturize.fixer_util import Assign, Comma, Call, Newline, Name, Number, indentation, suitify, commatize, token, syms, Node, Leaf def assignment_source(num_pre, num_post, LISTNAME, ITERNAME): u""" Accepts num_pre and num_post, which are counts of values before and after the starg (not including the starg) Returns a source fit for Assign() from fixer_util """ children = [] pre = unicode(num_pre) post = unicode(num_post) # This code builds the assignment source from lib2to3 tree primitives. # It's not very readable, but it seems like the most correct way to do it. if num_pre > 0: pre_part = Node(syms.power, [Name(LISTNAME), Node(syms.trailer, [Leaf(token.LSQB, u"["), Node(syms.subscript, [Leaf(token.COLON, u":"), Number(pre)]), Leaf(token.RSQB, u"]")])]) children.append(pre_part) children.append(Leaf(token.PLUS, u"+", prefix=u" ")) main_part = Node(syms.power, [Leaf(token.LSQB, u"[", prefix=u" "), Name(LISTNAME), Node(syms.trailer, [Leaf(token.LSQB, u"["), Node(syms.subscript, [Number(pre) if num_pre > 0 else Leaf(1, u""), Leaf(token.COLON, u":"), Node(syms.factor, [Leaf(token.MINUS, u"-"), Number(post)]) if num_post > 0 else Leaf(1, u"")]), Leaf(token.RSQB, u"]"), Leaf(token.RSQB, u"]")])]) children.append(main_part) if num_post > 0: children.append(Leaf(token.PLUS, u"+", prefix=u" ")) post_part = Node(syms.power, [Name(LISTNAME, prefix=u" "), Node(syms.trailer, [Leaf(token.LSQB, u"["), Node(syms.subscript, [Node(syms.factor, [Leaf(token.MINUS, u"-"), Number(post)]), Leaf(token.COLON, u":")]), Leaf(token.RSQB, u"]")])]) children.append(post_part) source = Node(syms.arith_expr, children) return source class FixUnpacking(fixer_base.BaseFix): PATTERN = u""" expl=expr_stmt< testlist_star_expr< pre=(any ',')* star_expr< '*' name=NAME > post=(',' any)* [','] > '=' source=any > | impl=for_stmt< 'for' lst=exprlist< pre=(any ',')* star_expr< '*' name=NAME > post=(',' any)* [','] > 'in' it=any ':' suite=any>""" def fix_explicit_context(self, node, results): pre, name, post, source = (results.get(n) for n in (u"pre", u"name", u"post", u"source")) pre = [n.clone() for n in pre if n.type == token.NAME] name.prefix = u" " post = [n.clone() for n in post if n.type == token.NAME] target = [n.clone() for n in commatize(pre + [name.clone()] + post)] # to make the special-case fix for "*z, = ..." correct with the least # amount of modification, make the left-side into a guaranteed tuple target.append(Comma()) source.prefix = u"" setup_line = Assign(Name(self.LISTNAME), Call(Name(u"list"), [source.clone()])) power_line = Assign(target, assignment_source(len(pre), len(post), self.LISTNAME, self.ITERNAME)) return setup_line, power_line def fix_implicit_context(self, node, results): u""" Only example of the implicit context is a for loop, so only fix that. """ pre, name, post, it = (results.get(n) for n in (u"pre", u"name", u"post", u"it")) pre = [n.clone() for n in pre if n.type == token.NAME] name.prefix = u" " post = [n.clone() for n in post if n.type == token.NAME] target = [n.clone() for n in commatize(pre + [name.clone()] + post)] # to make the special-case fix for "*z, = ..." correct with the least # amount of modification, make the left-side into a guaranteed tuple target.append(Comma()) source = it.clone() source.prefix = u"" setup_line = Assign(Name(self.LISTNAME), Call(Name(u"list"), [Name(self.ITERNAME)])) power_line = Assign(target, assignment_source(len(pre), len(post), self.LISTNAME, self.ITERNAME)) return setup_line, power_line def transform(self, node, results): u""" a,b,c,d,e,f,*g,h,i = range(100) changes to _3to2list = list(range(100)) a,b,c,d,e,f,g,h,i, = _3to2list[:6] + [_3to2list[6:-2]] + _3to2list[-2:] and for a,b,*c,d,e in iter_of_iters: do_stuff changes to for _3to2iter in iter_of_iters: _3to2list = list(_3to2iter) a,b,c,d,e, = _3to2list[:2] + [_3to2list[2:-2]] + _3to2list[-2:] do_stuff """ self.LISTNAME = self.new_name(u"_3to2list") self.ITERNAME = self.new_name(u"_3to2iter") expl, impl = results.get(u"expl"), results.get(u"impl") if expl is not None: setup_line, power_line = self.fix_explicit_context(node, results) setup_line.prefix = expl.prefix power_line.prefix = indentation(expl.parent) setup_line.append_child(Newline()) parent = node.parent i = node.remove() parent.insert_child(i, power_line) parent.insert_child(i, setup_line) elif impl is not None: setup_line, power_line = self.fix_implicit_context(node, results) suitify(node) suite = [k for k in node.children if k.type == syms.suite][0] setup_line.prefix = u"" power_line.prefix = suite.children[1].value suite.children[2].prefix = indentation(suite.children[2]) suite.insert_child(2, Newline()) suite.insert_child(2, power_line) suite.insert_child(2, Newline()) suite.insert_child(2, setup_line) results.get(u"lst").replace(Name(self.ITERNAME, prefix=u" "))
5,954
48.214876
370
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_imports.py
u""" Fixer for standard library imports renamed in Python 3 """ from lib2to3 import fixer_base from lib2to3.fixer_util import Name, is_probably_builtin, Newline, does_tree_import from lib2to3.pygram import python_symbols as syms from lib2to3.pgen2 import token from lib2to3.pytree import Node, Leaf from libfuturize.fixer_util import touch_import_top # from ..fixer_util import NameImport # used in simple_mapping_to_pattern() MAPPING = {u"reprlib": u"repr", u"winreg": u"_winreg", u"configparser": u"ConfigParser", u"copyreg": u"copy_reg", u"queue": u"Queue", u"socketserver": u"SocketServer", u"_markupbase": u"markupbase", u"test.support": u"test.test_support", u"dbm.bsd": u"dbhash", u"dbm.ndbm": u"dbm", u"dbm.dumb": u"dumbdbm", u"dbm.gnu": u"gdbm", u"html.parser": u"HTMLParser", u"html.entities": u"htmlentitydefs", u"http.client": u"httplib", u"http.cookies": u"Cookie", u"http.cookiejar": u"cookielib", # "tkinter": "Tkinter", u"tkinter.dialog": u"Dialog", u"tkinter._fix": u"FixTk", u"tkinter.scrolledtext": u"ScrolledText", u"tkinter.tix": u"Tix", u"tkinter.constants": u"Tkconstants", u"tkinter.dnd": u"Tkdnd", u"tkinter.__init__": u"Tkinter", u"tkinter.colorchooser": u"tkColorChooser", u"tkinter.commondialog": u"tkCommonDialog", u"tkinter.font": u"tkFont", u"tkinter.ttk": u"ttk", u"tkinter.messagebox": u"tkMessageBox", u"tkinter.turtle": u"turtle", u"urllib.robotparser": u"robotparser", u"xmlrpc.client": u"xmlrpclib", u"builtins": u"__builtin__", } # generic strings to help build patterns # these variables mean (with http.client.HTTPConnection as an example): # name = http # attr = client # used = HTTPConnection # fmt_name is a formatted subpattern (simple_name_match or dotted_name_match) # helps match 'queue', as in 'from queue import ...' simple_name_match = u"name='%s'" # helps match 'client', to be used if client has been imported from http subname_match = u"attr='%s'" # helps match 'http.client', as in 'import urllib.request' dotted_name_match = u"dotted_name=dotted_name< %s '.' %s >" # helps match 'queue', as in 'queue.Queue(...)' power_onename_match = u"%s" # helps match 'http.client', as in 'http.client.HTTPConnection(...)' power_twoname_match = u"power< %s trailer< '.' %s > any* >" # helps match 'client.HTTPConnection', if 'client' has been imported from http power_subname_match = u"power< %s any* >" # helps match 'from http.client import HTTPConnection' from_import_match = u"from_import=import_from< 'from' %s 'import' imported=any >" # helps match 'from http import client' from_import_submod_match = u"from_import_submod=import_from< 'from' %s 'import' (%s | import_as_name< %s 'as' renamed=any > | import_as_names< any* (%s | import_as_name< %s 'as' renamed=any >) any* > ) >" # helps match 'import urllib.request' name_import_match = u"name_import=import_name< 'import' %s > | name_import=import_name< 'import' dotted_as_name< %s 'as' renamed=any > >" # helps match 'import http.client, winreg' multiple_name_import_match = u"name_import=import_name< 'import' dotted_as_names< names=any* > >" def all_patterns(name): u""" Accepts a string and returns a pattern of possible patterns involving that name Called by simple_mapping_to_pattern for each name in the mapping it receives. """ # i_ denotes an import-like node # u_ denotes a node that appears to be a usage of the name if u'.' in name: name, attr = name.split(u'.', 1) simple_name = simple_name_match % (name) simple_attr = subname_match % (attr) dotted_name = dotted_name_match % (simple_name, simple_attr) i_from = from_import_match % (dotted_name) i_from_submod = from_import_submod_match % (simple_name, simple_attr, simple_attr, simple_attr, simple_attr) i_name = name_import_match % (dotted_name, dotted_name) u_name = power_twoname_match % (simple_name, simple_attr) u_subname = power_subname_match % (simple_attr) return u' | \n'.join((i_name, i_from, i_from_submod, u_name, u_subname)) else: simple_name = simple_name_match % (name) i_name = name_import_match % (simple_name, simple_name) i_from = from_import_match % (simple_name) u_name = power_onename_match % (simple_name) return u' | \n'.join((i_name, i_from, u_name)) class FixImports(fixer_base.BaseFix): PATTERN = u' | \n'.join([all_patterns(name) for name in MAPPING]) PATTERN = u' | \n'.join((PATTERN, multiple_name_import_match)) def transform(self, node, results): touch_import_top(u'future', u'standard_library', node)
4,945
42.385965
204
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/__init__.py
import sys from lib2to3 import refactor # The original set of these fixes comes from lib3to2 (https://bitbucket.org/amentajo/lib3to2): fix_names = set([ 'libpasteurize.fixes.fix_add_all__future__imports', # from __future__ import absolute_import etc. on separate lines 'libpasteurize.fixes.fix_add_future_standard_library_import', # we force adding this import for now, even if it doesn't seem necessary to the fix_future_standard_library fixer, for ease of testing # 'libfuturize.fixes.fix_order___future__imports', # consolidates to a single line to simplify testing -- UNFINISHED 'libpasteurize.fixes.fix_future_builtins', # adds "from future.builtins import *" 'libfuturize.fixes.fix_future_standard_library', # adds "from future import standard_library" 'libpasteurize.fixes.fix_annotations', # 'libpasteurize.fixes.fix_bitlength', # ints have this in Py2.7 # 'libpasteurize.fixes.fix_bool', # need a decorator or Mixin # 'libpasteurize.fixes.fix_bytes', # leave bytes as bytes # 'libpasteurize.fixes.fix_classdecorator', # available in # Py2.6+ # 'libpasteurize.fixes.fix_collections', hmmm ... # 'libpasteurize.fixes.fix_dctsetcomp', # avail in Py27 'libpasteurize.fixes.fix_division', # yes # 'libpasteurize.fixes.fix_except', # avail in Py2.6+ # 'libpasteurize.fixes.fix_features', # ? 'libpasteurize.fixes.fix_fullargspec', # 'libpasteurize.fixes.fix_funcattrs', 'libpasteurize.fixes.fix_getcwd', 'libpasteurize.fixes.fix_imports', # adds "from future import standard_library" 'libpasteurize.fixes.fix_imports2', # 'libpasteurize.fixes.fix_input', # 'libpasteurize.fixes.fix_int', # 'libpasteurize.fixes.fix_intern', # 'libpasteurize.fixes.fix_itertools', 'libpasteurize.fixes.fix_kwargs', # yes, we want this # 'libpasteurize.fixes.fix_memoryview', # 'libpasteurize.fixes.fix_metaclass', # write a custom handler for # this # 'libpasteurize.fixes.fix_methodattrs', # __func__ and __self__ seem to be defined on Py2.7 already 'libpasteurize.fixes.fix_newstyle', # yes, we want this: explicit inheritance from object. Without new-style classes in Py2, super() will break etc. # 'libpasteurize.fixes.fix_next', # use a decorator for this # 'libpasteurize.fixes.fix_numliterals', # prob not # 'libpasteurize.fixes.fix_open', # huh? # 'libpasteurize.fixes.fix_print', # no way 'libpasteurize.fixes.fix_printfunction', # adds __future__ import print_function # 'libpasteurize.fixes.fix_raise_', # TODO: get this working! # 'libpasteurize.fixes.fix_range', # nope # 'libpasteurize.fixes.fix_reduce', # 'libpasteurize.fixes.fix_setliteral', # 'libpasteurize.fixes.fix_str', # 'libpasteurize.fixes.fix_super', # maybe, if our magic super() isn't robust enough 'libpasteurize.fixes.fix_throw', # yes, if Py3 supports it # 'libpasteurize.fixes.fix_unittest', 'libpasteurize.fixes.fix_unpacking', # yes, this is useful # 'libpasteurize.fixes.fix_with' # way out of date ])
3,720
65.446429
214
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_imports2.py
u""" Fixer for complicated imports """ from lib2to3 import fixer_base from lib2to3.fixer_util import Name, String, FromImport, Newline, Comma from libfuturize.fixer_util import touch_import_top TK_BASE_NAMES = (u'ACTIVE', u'ALL', u'ANCHOR', u'ARC',u'BASELINE', u'BEVEL', u'BOTH', u'BOTTOM', u'BROWSE', u'BUTT', u'CASCADE', u'CENTER', u'CHAR', u'CHECKBUTTON', u'CHORD', u'COMMAND', u'CURRENT', u'DISABLED', u'DOTBOX', u'E', u'END', u'EW', u'EXCEPTION', u'EXTENDED', u'FALSE', u'FIRST', u'FLAT', u'GROOVE', u'HIDDEN', u'HORIZONTAL', u'INSERT', u'INSIDE', u'LAST', u'LEFT', u'MITER', u'MOVETO', u'MULTIPLE', u'N', u'NE', u'NO', u'NONE', u'NORMAL', u'NS', u'NSEW', u'NUMERIC', u'NW', u'OFF', u'ON', u'OUTSIDE', u'PAGES', u'PIESLICE', u'PROJECTING', u'RADIOBUTTON', u'RAISED', u'READABLE', u'RIDGE', u'RIGHT', u'ROUND', u'S', u'SCROLL', u'SE', u'SEL', u'SEL_FIRST', u'SEL_LAST', u'SEPARATOR', u'SINGLE', u'SOLID', u'SUNKEN', u'SW', u'StringTypes', u'TOP', u'TRUE', u'TclVersion', u'TkVersion', u'UNDERLINE', u'UNITS', u'VERTICAL', u'W', u'WORD', u'WRITABLE', u'X', u'Y', u'YES', u'wantobjects') PY2MODULES = { u'urllib2' : ( u'AbstractBasicAuthHandler', u'AbstractDigestAuthHandler', u'AbstractHTTPHandler', u'BaseHandler', u'CacheFTPHandler', u'FTPHandler', u'FileHandler', u'HTTPBasicAuthHandler', u'HTTPCookieProcessor', u'HTTPDefaultErrorHandler', u'HTTPDigestAuthHandler', u'HTTPError', u'HTTPErrorProcessor', u'HTTPHandler', u'HTTPPasswordMgr', u'HTTPPasswordMgrWithDefaultRealm', u'HTTPRedirectHandler', u'HTTPSHandler', u'OpenerDirector', u'ProxyBasicAuthHandler', u'ProxyDigestAuthHandler', u'ProxyHandler', u'Request', u'StringIO', u'URLError', u'UnknownHandler', u'addinfourl', u'build_opener', u'install_opener', u'parse_http_list', u'parse_keqv_list', u'randombytes', u'request_host', u'urlopen'), u'urllib' : ( u'ContentTooShortError', u'FancyURLopener',u'URLopener', u'basejoin', u'ftperrors', u'getproxies', u'getproxies_environment', u'localhost', u'pathname2url', u'quote', u'quote_plus', u'splitattr', u'splithost', u'splitnport', u'splitpasswd', u'splitport', u'splitquery', u'splittag', u'splittype', u'splituser', u'splitvalue', u'thishost', u'unquote', u'unquote_plus', u'unwrap', u'url2pathname', u'urlcleanup', u'urlencode', u'urlopen', u'urlretrieve',), u'urlparse' : ( u'parse_qs', u'parse_qsl', u'urldefrag', u'urljoin', u'urlparse', u'urlsplit', u'urlunparse', u'urlunsplit'), u'dbm' : ( u'ndbm', u'gnu', u'dumb'), u'anydbm' : ( u'error', u'open'), u'whichdb' : ( u'whichdb',), u'BaseHTTPServer' : ( u'BaseHTTPRequestHandler', u'HTTPServer'), u'CGIHTTPServer' : ( u'CGIHTTPRequestHandler',), u'SimpleHTTPServer' : ( u'SimpleHTTPRequestHandler',), u'FileDialog' : TK_BASE_NAMES + ( u'FileDialog', u'LoadFileDialog', u'SaveFileDialog', u'dialogstates', u'test'), u'tkFileDialog' : ( u'Directory', u'Open', u'SaveAs', u'_Dialog', u'askdirectory', u'askopenfile', u'askopenfilename', u'askopenfilenames', u'askopenfiles', u'asksaveasfile', u'asksaveasfilename'), u'SimpleDialog' : TK_BASE_NAMES + ( u'SimpleDialog',), u'tkSimpleDialog' : TK_BASE_NAMES + ( u'askfloat', u'askinteger', u'askstring', u'Dialog'), u'SimpleXMLRPCServer' : ( u'CGIXMLRPCRequestHandler', u'SimpleXMLRPCDispatcher', u'SimpleXMLRPCRequestHandler', u'SimpleXMLRPCServer', u'list_public_methods', u'remove_duplicates', u'resolve_dotted_attribute'), u'DocXMLRPCServer' : ( u'DocCGIXMLRPCRequestHandler', u'DocXMLRPCRequestHandler', u'DocXMLRPCServer', u'ServerHTMLDoc',u'XMLRPCDocGenerator'), } MAPPING = { u'urllib.request' : (u'urllib2', u'urllib'), u'urllib.error' : (u'urllib2', u'urllib'), u'urllib.parse' : (u'urllib2', u'urllib', u'urlparse'), u'dbm.__init__' : (u'anydbm', u'whichdb'), u'http.server' : (u'CGIHTTPServer', u'SimpleHTTPServer', u'BaseHTTPServer'), u'tkinter.filedialog' : (u'tkFileDialog', u'FileDialog'), u'tkinter.simpledialog' : (u'tkSimpleDialog', u'SimpleDialog'), u'xmlrpc.server' : (u'DocXMLRPCServer', u'SimpleXMLRPCServer'), } # helps match 'http', as in 'from http.server import ...' simple_name = u"name='%s'" # helps match 'server', as in 'from http.server import ...' simple_attr = u"attr='%s'" # helps match 'HTTPServer', as in 'from http.server import HTTPServer' simple_using = u"using='%s'" # helps match 'urllib.request', as in 'import urllib.request' dotted_name = u"dotted_name=dotted_name< %s '.' %s >" # helps match 'http.server', as in 'http.server.HTTPServer(...)' power_twoname = u"pow=power< %s trailer< '.' %s > trailer< '.' using=any > any* >" # helps match 'dbm.whichdb', as in 'dbm.whichdb(...)' power_onename = u"pow=power< %s trailer< '.' using=any > any* >" # helps match 'from http.server import HTTPServer' # also helps match 'from http.server import HTTPServer, SimpleHTTPRequestHandler' # also helps match 'from http.server import *' from_import = u"from_import=import_from< 'from' %s 'import' (import_as_name< using=any 'as' renamed=any> | in_list=import_as_names< using=any* > | using='*' | using=NAME) >" # helps match 'import urllib.request' name_import = u"name_import=import_name< 'import' (%s | in_list=dotted_as_names< imp_list=any* >) >" ############# # WON'T FIX # ############# # helps match 'import urllib.request as name' name_import_rename = u"name_import_rename=dotted_as_name< %s 'as' renamed=any >" # helps match 'from http import server' from_import_rename = u"from_import_rename=import_from< 'from' %s 'import' (%s | import_as_name< %s 'as' renamed=any > | in_list=import_as_names< any* (%s | import_as_name< %s 'as' renamed=any >) any* >) >" def all_modules_subpattern(): u""" Builds a pattern for all toplevel names (urllib, http, etc) """ names_dot_attrs = [mod.split(u".") for mod in MAPPING] ret = u"( " + u" | ".join([dotted_name % (simple_name % (mod[0]), simple_attr % (mod[1])) for mod in names_dot_attrs]) ret += u" | " ret += u" | ".join([simple_name % (mod[0]) for mod in names_dot_attrs if mod[1] == u"__init__"]) + u" )" return ret def build_import_pattern(mapping1, mapping2): u""" mapping1: A dict mapping py3k modules to all possible py2k replacements mapping2: A dict mapping py2k modules to the things they do This builds a HUGE pattern to match all ways that things can be imported """ # py3k: urllib.request, py2k: ('urllib2', 'urllib') yield from_import % (all_modules_subpattern()) for py3k, py2k in mapping1.items(): name, attr = py3k.split(u'.') s_name = simple_name % (name) s_attr = simple_attr % (attr) d_name = dotted_name % (s_name, s_attr) yield name_import % (d_name) yield power_twoname % (s_name, s_attr) if attr == u'__init__': yield name_import % (s_name) yield power_onename % (s_name) yield name_import_rename % (d_name) yield from_import_rename % (s_name, s_attr, s_attr, s_attr, s_attr) class FixImports2(fixer_base.BaseFix): run_order = 4 PATTERN = u" | \n".join(build_import_pattern(MAPPING, PY2MODULES)) def transform(self, node, results): touch_import_top(u'future', u'standard_library', node)
8,583
47.772727
205
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_next.py
u""" Fixer for: it.__next__() -> it.next(). next(it) -> it.next(). """ from lib2to3.pgen2 import token from lib2to3.pygram import python_symbols as syms from lib2to3 import fixer_base from lib2to3.fixer_util import Name, Call, find_binding, Attr bind_warning = u"Calls to builtin next() possibly shadowed by global binding" class FixNext(fixer_base.BaseFix): PATTERN = u""" power< base=any+ trailer< '.' attr='__next__' > any* > | power< head='next' trailer< '(' arg=any ')' > any* > | classdef< 'class' base=any+ ':' suite< any* funcdef< 'def' attr='__next__' parameters< '(' NAME ')' > any+ > any* > > """ def transform(self, node, results): assert results base = results.get(u"base") attr = results.get(u"attr") head = results.get(u"head") arg_ = results.get(u"arg") if arg_: arg = arg_.clone() head.replace(Attr(Name(unicode(arg),prefix=head.prefix), Name(u"next"))) arg_.remove() elif base: attr.replace(Name(u"next", prefix=attr.prefix))
1,233
27.045455
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_add_all_future_builtins.py
""" For the ``future`` package. Adds this import line:: from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, list, map, next, object, oct, open, pow, range, round, str, super, zip) to a module, irrespective of whether each definition is used. Adds these imports after any other imports (in an initial block of them). """ from __future__ import unicode_literals from lib2to3 import fixer_base from libfuturize.fixer_util import touch_import_top class FixAddAllFutureBuiltins(fixer_base.BaseFix): BM_compatible = True PATTERN = "file_input" run_order = 1 def transform(self, node, results): # import_str = """(ascii, bytes, chr, dict, filter, hex, input, # int, list, map, next, object, oct, open, pow, # range, round, str, super, zip)""" touch_import_top(u'builtins', '*', node) # builtins = """ascii bytes chr dict filter hex input # int list map next object oct open pow # range round str super zip""" # for builtin in sorted(builtins.split(), reverse=True): # touch_import_top(u'builtins', builtin, node)
1,270
31.589744
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/libpasteurize/fixes/fix_features.py
u""" Warn about features that are not present in Python 2.5, giving a message that points to the earliest version of Python 2.x (or 3.x, if none) that supports it """ from .feature_base import Feature, Features from lib2to3 import fixer_base FEATURES = [ #(FeatureName, # FeaturePattern, # FeatureMinVersion, #), (u"memoryview", u"power < 'memoryview' trailer < '(' any* ')' > any* >", u"2.7", ), (u"numbers", u"""import_from< 'from' 'numbers' 'import' any* > | import_name< 'import' ('numbers' dotted_as_names< any* 'numbers' any* >) >""", u"2.6", ), (u"abc", u"""import_name< 'import' ('abc' dotted_as_names< any* 'abc' any* >) > | import_from< 'from' 'abc' 'import' any* >""", u"2.6", ), (u"io", u"""import_name< 'import' ('io' dotted_as_names< any* 'io' any* >) > | import_from< 'from' 'io' 'import' any* >""", u"2.6", ), (u"bin", u"power< 'bin' trailer< '(' any* ')' > any* >", u"2.6", ), (u"formatting", u"power< any trailer< '.' 'format' > trailer< '(' any* ')' > >", u"2.6", ), (u"nonlocal", u"global_stmt< 'nonlocal' any* >", u"3.0", ), (u"with_traceback", u"trailer< '.' 'with_traceback' >", u"3.0", ), ] class FixFeatures(fixer_base.BaseFix): run_order = 9 # Wait until all other fixers have run to check for these # To avoid spamming, we only want to warn for each feature once. features_warned = set() # Build features from the list above features = Features([Feature(name, pattern, version) for \ name, pattern, version in FEATURES]) PATTERN = features.PATTERN def match(self, node): to_ret = super(FixFeatures, self).match(node) # We want the mapping only to tell us the node's specific information. try: del to_ret[u'node'] except Exception: # We want it to delete the 'node' from the results # if it's there, so we don't care if it fails for normal reasons. pass return to_ret def transform(self, node, results): for feature_name in results: if feature_name in self.features_warned: continue else: curr_feature = self.features[feature_name] if curr_feature.version >= u"3": fail = self.cannot_convert else: fail = self.warning fail(node, reason=curr_feature.message_text()) self.features_warned.add(feature_name)
2,679
29.804598
89
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/easter.py
# -*- coding: utf-8 -*- """ This module offers a generic easter computing method for any given year, using Western, Orthodox or Julian algorithms. """ import datetime __all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] EASTER_JULIAN = 1 EASTER_ORTHODOX = 2 EASTER_WESTERN = 3 def easter(year, method=EASTER_WESTERN): """ This method was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, editor. This algorithm implements three different easter calculation methods: 1 - Original calculation in Julian calendar, valid in dates after 326 AD 2 - Original method, with date converted to Gregorian calendar, valid in years 1583 to 4099 3 - Revised method, in Gregorian calendar, valid in years 1583 to 4099 as well These methods are represented by the constants: * ``EASTER_JULIAN = 1`` * ``EASTER_ORTHODOX = 2`` * ``EASTER_WESTERN = 3`` The default method is method 3. More about the algorithm may be found at: `GM Arts: Easter Algorithms <http://www.gmarts.org/index.php?go=415>`_ and `The Calendar FAQ: Easter <https://www.tondering.dk/claus/cal/easter.php>`_ """ if not (1 <= method <= 3): raise ValueError("invalid method") # g - Golden year - 1 # c - Century # h - (23 - Epact) mod 30 # i - Number of days from March 21 to Paschal Full Moon # j - Weekday for PFM (0=Sunday, etc) # p - Number of days from March 21 to Sunday on or before PFM # (-6 to 28 methods 1 & 3, to 56 for method 2) # e - Extra days to add for method 2 (converting Julian # date to Gregorian date) y = year g = y % 19 e = 0 if method < 3: # Old method i = (19*g + 15) % 30 j = (y + y//4 + i) % 7 if method == 2: # Extra dates to convert Julian to Gregorian date e = 10 if y > 1600: e = e + y//100 - 16 - (y//100 - 16)//4 else: # New method c = y//100 h = (c - c//4 - (8*c + 13)//25 + 19*g + 15) % 30 i = h - (h//28)*(1 - (h//28)*(29//(h + 1))*((21 - g)//11)) j = (y + y//4 + i + 2 - c + c//4) % 7 # p can be from -6 to 56 corresponding to dates 22 March to 23 May # (later dates apply to method 2, although 23 May never actually occurs) p = i - j + e d = 1 + (p + 27 + (p + 6)//40) % 31 m = 3 + (p + 26)//30 return datetime.date(int(y), int(m), int(d))
2,684
28.833333
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/tzwin.py
# tzwin has moved to dateutil.tz.win from .tz.win import *
59
19
36
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/utils.py
# -*- coding: utf-8 -*- """ This module offers general convenience and utility functions for dealing with datetimes. .. versionadded:: 2.7.0 """ from __future__ import unicode_literals from datetime import datetime, time def today(tzinfo=None): """ Returns a :py:class:`datetime` representing the current day at midnight :param tzinfo: The time zone to attach (also used to determine the current day). :return: A :py:class:`datetime.datetime` object representing the current day at midnight. """ dt = datetime.now(tzinfo) return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) def default_tzinfo(dt, tzinfo): """ Sets the the ``tzinfo`` parameter on naive datetimes only This is useful for example when you are provided a datetime that may have either an implicit or explicit time zone, such as when parsing a time zone string. .. doctest:: >>> from dateutil.tz import tzoffset >>> from dateutil.parser import parse >>> from dateutil.utils import default_tzinfo >>> dflt_tz = tzoffset("EST", -18000) >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) 2014-01-01 12:30:00+00:00 >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) 2014-01-01 12:30:00-05:00 :param dt: The datetime on which to replace the time zone :param tzinfo: The :py:class:`datetime.tzinfo` subclass instance to assign to ``dt`` if (and only if) it is naive. :return: Returns an aware :py:class:`datetime.datetime`. """ if dt.tzinfo is not None: return dt else: return dt.replace(tzinfo=tzinfo) def within_delta(dt1, dt2, delta): """ Useful for comparing two datetimes that may a negilible difference to be considered equal. """ delta = abs(delta) difference = dt1 - dt2 return -delta <= difference <= delta
1,963
26.277778
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/_version.py
# coding: utf-8 # file generated by setuptools_scm # don't change, don't track in version control version = '2.7.3'
116
22.4
46
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/relativedelta.py
# -*- coding: utf-8 -*- import datetime import calendar import operator from math import copysign from six import integer_types from warnings import warn from ._common import weekday MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) __all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] class relativedelta(object): """ The relativedelta type is based on the specification of the excellent work done by M.-A. Lemburg in his `mx.DateTime <https://www.egenix.com/products/python/mxBase/mxDateTime/>`_ extension. However, notice that this type does *NOT* implement the same algorithm as his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. There are two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes:: relativedelta(datetime1, datetime2) The second one is passing it any number of the following keyword arguments:: relativedelta(arg1=x,arg2=y,arg3=z...) year, month, day, hour, minute, second, microsecond: Absolute information (argument is singular); adding or subtracting a relativedelta with absolute information does not perform an arithmetic operation, but rather REPLACES the corresponding value in the original datetime with the value(s) in relativedelta. years, months, weeks, days, hours, minutes, seconds, microseconds: Relative information, may be negative (argument is plural); adding or subtracting a relativedelta with relative information performs the corresponding aritmetic operation on the original datetime value with the information in the relativedelta. weekday: One of the weekday instances (MO, TU, etc). These instances may receive a parameter N, specifying the Nth weekday, which could be positive or negative (like MO(+1) or MO(-2). Not specifying it is the same as specifying +1. You can also use an integer, where 0=MO. Notice that if the calculated date is already Monday, for example, using MO(1) or MO(-1) won't change the day. leapdays: Will add given days to the date found, if year is a leap year, and the date found is post 28 of february. yearday, nlyearday: Set the yearday or the non-leap year day (jump leap days). These are converted to day/month/leapdays information. There are relative and absolute forms of the keyword arguments. The plural is relative, and the singular is absolute. For each argument in the order below, the absolute form is applied first (by setting each attribute to that value) and then the relative form (by adding the value to the attribute). The order of attributes considered when this relativedelta is added to a datetime is: 1. Year 2. Month 3. Day 4. Hours 5. Minutes 6. Seconds 7. Microseconds Finally, weekday is applied, using the rule described above. For example >>> dt = datetime(2018, 4, 9, 13, 37, 0) >>> delta = relativedelta(hours=25, day=1, weekday=MO(1)) datetime(2018, 4, 2, 14, 37, 0) First, the day is set to 1 (the first of the month), then 25 hours are added, to get to the 2nd day and 14th hour, finally the weekday is applied, but since the 2nd is already a Monday there is no effect. """ def __init__(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None): if dt1 and dt2: # datetime is a subclass of date. So both must be date if not (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date)): raise TypeError("relativedelta only diffs datetime/date") # We allow two dates, or two datetimes, so we coerce them to be # of the same type if (isinstance(dt1, datetime.datetime) != isinstance(dt2, datetime.datetime)): if not isinstance(dt1, datetime.datetime): dt1 = datetime.datetime.fromordinal(dt1.toordinal()) elif not isinstance(dt2, datetime.datetime): dt2 = datetime.datetime.fromordinal(dt2.toordinal()) self.years = 0 self.months = 0 self.days = 0 self.leapdays = 0 self.hours = 0 self.minutes = 0 self.seconds = 0 self.microseconds = 0 self.year = None self.month = None self.day = None self.weekday = None self.hour = None self.minute = None self.second = None self.microsecond = None self._has_time = 0 # Get year / month delta between the two months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month) self._set_months(months) # Remove the year/month delta so the timedelta is just well-defined # time units (seconds, days and microseconds) dtm = self.__radd__(dt2) # If we've overshot our target, make an adjustment if dt1 < dt2: compare = operator.gt increment = 1 else: compare = operator.lt increment = -1 while compare(dt1, dtm): months += increment self._set_months(months) dtm = self.__radd__(dt2) # Get the timedelta between the "months-adjusted" date and dt1 delta = dt1 - dtm self.seconds = delta.seconds + delta.days * 86400 self.microseconds = delta.microseconds else: # Check for non-integer values in integer-only quantities if any(x is not None and x != int(x) for x in (years, months)): raise ValueError("Non-integer years and months are " "ambiguous and not currently supported.") # Relative information self.years = int(years) self.months = int(months) self.days = days + weeks * 7 self.leapdays = leapdays self.hours = hours self.minutes = minutes self.seconds = seconds self.microseconds = microseconds # Absolute information self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.microsecond = microsecond if any(x is not None and int(x) != x for x in (year, month, day, hour, minute, second, microsecond)): # For now we'll deprecate floats - later it'll be an error. warn("Non-integer value passed as absolute information. " + "This is not a well-defined condition and will raise " + "errors in future versions.", DeprecationWarning) if isinstance(weekday, integer_types): self.weekday = weekdays[weekday] else: self.weekday = weekday yday = 0 if nlyearday: yday = nlyearday elif yearday: yday = yearday if yearday > 59: self.leapdays = -1 if yday: ydayidx = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 366] for idx, ydays in enumerate(ydayidx): if yday <= ydays: self.month = idx+1 if idx == 0: self.day = yday else: self.day = yday-ydayidx[idx-1] break else: raise ValueError("invalid year day (%d)" % yday) self._fix() def _fix(self): if abs(self.microseconds) > 999999: s = _sign(self.microseconds) div, mod = divmod(self.microseconds * s, 1000000) self.microseconds = mod * s self.seconds += div * s if abs(self.seconds) > 59: s = _sign(self.seconds) div, mod = divmod(self.seconds * s, 60) self.seconds = mod * s self.minutes += div * s if abs(self.minutes) > 59: s = _sign(self.minutes) div, mod = divmod(self.minutes * s, 60) self.minutes = mod * s self.hours += div * s if abs(self.hours) > 23: s = _sign(self.hours) div, mod = divmod(self.hours * s, 24) self.hours = mod * s self.days += div * s if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years += div * s if (self.hours or self.minutes or self.seconds or self.microseconds or self.hour is not None or self.minute is not None or self.second is not None or self.microsecond is not None): self._has_time = 1 else: self._has_time = 0 @property def weeks(self): return int(self.days / 7.0) @weeks.setter def weeks(self, value): self.days = self.days - (self.weeks * 7) + value * 7 def _set_months(self, months): self.months = months if abs(self.months) > 11: s = _sign(self.months) div, mod = divmod(self.months * s, 12) self.months = mod * s self.years = div * s else: self.years = 0 def normalized(self): """ Return a version of this object represented entirely using integer values for the relative attributes. >>> relativedelta(days=1.5, hours=2).normalized() relativedelta(days=1, hours=14) :return: Returns a :class:`dateutil.relativedelta.relativedelta` object. """ # Cascade remainders down (rounding each to roughly nearest microsecond) days = int(self.days) hours_f = round(self.hours + 24 * (self.days - days), 11) hours = int(hours_f) minutes_f = round(self.minutes + 60 * (hours_f - hours), 10) minutes = int(minutes_f) seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8) seconds = int(seconds_f) microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds)) # Constructor carries overflow back up with call to _fix() return self.__class__(years=self.years, months=self.months, days=days, hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __add__(self, other): if isinstance(other, relativedelta): return self.__class__(years=other.years + self.years, months=other.months + self.months, days=other.days + self.days, hours=other.hours + self.hours, minutes=other.minutes + self.minutes, seconds=other.seconds + self.seconds, microseconds=(other.microseconds + self.microseconds), leapdays=other.leapdays or self.leapdays, year=(other.year if other.year is not None else self.year), month=(other.month if other.month is not None else self.month), day=(other.day if other.day is not None else self.day), weekday=(other.weekday if other.weekday is not None else self.weekday), hour=(other.hour if other.hour is not None else self.hour), minute=(other.minute if other.minute is not None else self.minute), second=(other.second if other.second is not None else self.second), microsecond=(other.microsecond if other.microsecond is not None else self.microsecond)) if isinstance(other, datetime.timedelta): return self.__class__(years=self.years, months=self.months, days=self.days + other.days, hours=self.hours, minutes=self.minutes, seconds=self.seconds + other.seconds, microseconds=self.microseconds + other.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) if not isinstance(other, datetime.date): return NotImplemented elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth) - 1) * 7 if nth > 0: jumpdays += (7 - ret.weekday() + weekday) % 7 else: jumpdays += (ret.weekday() - weekday) % 7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): return self.__neg__().__radd__(other) def __sub__(self, other): if not isinstance(other, relativedelta): return NotImplemented # In case the other object defines __rsub__ return self.__class__(years=self.years - other.years, months=self.months - other.months, days=self.days - other.days, hours=self.hours - other.hours, minutes=self.minutes - other.minutes, seconds=self.seconds - other.seconds, microseconds=self.microseconds - other.microseconds, leapdays=self.leapdays or other.leapdays, year=(self.year if self.year is not None else other.year), month=(self.month if self.month is not None else other.month), day=(self.day if self.day is not None else other.day), weekday=(self.weekday if self.weekday is not None else other.weekday), hour=(self.hour if self.hour is not None else other.hour), minute=(self.minute if self.minute is not None else other.minute), second=(self.second if self.second is not None else other.second), microsecond=(self.microsecond if self.microsecond is not None else other.microsecond)) def __abs__(self): return self.__class__(years=abs(self.years), months=abs(self.months), days=abs(self.days), hours=abs(self.hours), minutes=abs(self.minutes), seconds=abs(self.seconds), microseconds=abs(self.microseconds), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __neg__(self): return self.__class__(years=-self.years, months=-self.months, days=-self.days, hours=-self.hours, minutes=-self.minutes, seconds=-self.seconds, microseconds=-self.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __bool__(self): return not (not self.years and not self.months and not self.days and not self.hours and not self.minutes and not self.seconds and not self.microseconds and not self.leapdays and self.year is None and self.month is None and self.day is None and self.weekday is None and self.hour is None and self.minute is None and self.second is None and self.microsecond is None) # Compatibility with Python 2.x __nonzero__ = __bool__ def __mul__(self, other): try: f = float(other) except TypeError: return NotImplemented return self.__class__(years=int(self.years * f), months=int(self.months * f), days=int(self.days * f), hours=int(self.hours * f), minutes=int(self.minutes * f), seconds=int(self.seconds * f), microseconds=int(self.microseconds * f), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) __rmul__ = __mul__ def __eq__(self, other): if not isinstance(other, relativedelta): return NotImplemented if self.weekday or other.weekday: if not self.weekday or not other.weekday: return False if self.weekday.weekday != other.weekday.weekday: return False n1, n2 = self.weekday.n, other.weekday.n if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): return False return (self.years == other.years and self.months == other.months and self.days == other.days and self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds and self.microseconds == other.microseconds and self.leapdays == other.leapdays and self.year == other.year and self.month == other.month and self.day == other.day and self.hour == other.hour and self.minute == other.minute and self.second == other.second and self.microsecond == other.microsecond) def __hash__(self): return hash(( self.weekday, self.years, self.months, self.days, self.hours, self.minutes, self.seconds, self.microseconds, self.leapdays, self.year, self.month, self.day, self.hour, self.minute, self.second, self.microsecond, )) def __ne__(self, other): return not self.__eq__(other) def __div__(self, other): try: reciprocal = 1 / float(other) except TypeError: return NotImplemented return self.__mul__(reciprocal) __truediv__ = __div__ def __repr__(self): l = [] for attr in ["years", "months", "days", "leapdays", "hours", "minutes", "seconds", "microseconds"]: value = getattr(self, attr) if value: l.append("{attr}={value:+g}".format(attr=attr, value=value)) for attr in ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: l.append("{attr}={value}".format(attr=attr, value=repr(value))) return "{classname}({attrs})".format(classname=self.__class__.__name__, attrs=", ".join(l)) def _sign(x): return int(copysign(1, x)) # vim:ts=4:sw=4:et
24,418
40.318105
89
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/rrule.py
# -*- coding: utf-8 -*- """ The rrule module offers a small, complete, and very fast, implementation of the recurrence rules documented in the `iCalendar RFC <https://tools.ietf.org/html/rfc5545>`_, including support for caching of results. """ import itertools import datetime import calendar import re import sys try: from math import gcd except ImportError: from fractions import gcd from six import advance_iterator, integer_types from six.moves import _thread, range import heapq from ._common import weekday as weekdaybase from .tz import tzutc, tzlocal # For warning about deprecation of until and count from warnings import warn __all__ = ["rrule", "rruleset", "rrulestr", "YEARLY", "MONTHLY", "WEEKLY", "DAILY", "HOURLY", "MINUTELY", "SECONDLY", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] # Every mask is 7 days longer to handle cross-year weekly periods. M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 + [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7) M365MASK = list(M366MASK) M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32)) MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) MDAY365MASK = list(MDAY366MASK) M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0)) NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) NMDAY365MASK = list(NMDAY366MASK) M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366) M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55 del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31] MDAY365MASK = tuple(MDAY365MASK) M365MASK = tuple(M365MASK) FREQNAMES = ['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY'] (YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY) = list(range(7)) # Imported on demand. easter = None parser = None class weekday(weekdaybase): """ This version of weekday does not allow n = 0. """ def __init__(self, wkday, n=None): if n == 0: raise ValueError("Can't create weekday with n==0") super(weekday, self).__init__(wkday, n) MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) def _invalidates_cache(f): """ Decorator for rruleset methods which may invalidate the cached length. """ def inner_func(self, *args, **kwargs): rv = f(self, *args, **kwargs) self._invalidate_cache() return rv return inner_func class rrulebase(object): def __init__(self, cache=False): if cache: self._cache = [] self._cache_lock = _thread.allocate_lock() self._invalidate_cache() else: self._cache = None self._cache_complete = False self._len = None def __iter__(self): if self._cache_complete: return iter(self._cache) elif self._cache is None: return self._iter() else: return self._iter_cached() def _invalidate_cache(self): if self._cache is not None: self._cache = [] self._cache_complete = False self._cache_gen = self._iter() if self._cache_lock.locked(): self._cache_lock.release() self._len = None def _iter_cached(self): i = 0 gen = self._cache_gen cache = self._cache acquire = self._cache_lock.acquire release = self._cache_lock.release while gen: if i == len(cache): acquire() if self._cache_complete: break try: for j in range(10): cache.append(advance_iterator(gen)) except StopIteration: self._cache_gen = gen = None self._cache_complete = True break release() yield cache[i] i += 1 while i < self._len: yield cache[i] i += 1 def __getitem__(self, item): if self._cache_complete: return self._cache[item] elif isinstance(item, slice): if item.step and item.step < 0: return list(iter(self))[item] else: return list(itertools.islice(self, item.start or 0, item.stop or sys.maxsize, item.step or 1)) elif item >= 0: gen = iter(self) try: for i in range(item+1): res = advance_iterator(gen) except StopIteration: raise IndexError return res else: return list(iter(self))[item] def __contains__(self, item): if self._cache_complete: return item in self._cache else: for i in self: if i == item: return True elif i > item: return False return False # __len__() introduces a large performance penality. def count(self): """ Returns the number of recurrences in this set. It will have go trough the whole recurrence, if this hasn't been done before. """ if self._len is None: for x in self: pass return self._len def before(self, dt, inc=False): """ Returns the last recurrence before the given datetime instance. The inc keyword defines what happens if dt is an occurrence. With inc=True, if dt itself is an occurrence, it will be returned. """ if self._cache_complete: gen = self._cache else: gen = self last = None if inc: for i in gen: if i > dt: break last = i else: for i in gen: if i >= dt: break last = i return last def after(self, dt, inc=False): """ Returns the first recurrence after the given datetime instance. The inc keyword defines what happens if dt is an occurrence. With inc=True, if dt itself is an occurrence, it will be returned. """ if self._cache_complete: gen = self._cache else: gen = self if inc: for i in gen: if i >= dt: return i else: for i in gen: if i > dt: return i return None def xafter(self, dt, count=None, inc=False): """ Generator which yields up to `count` recurrences after the given datetime instance, equivalent to `after`. :param dt: The datetime at which to start generating recurrences. :param count: The maximum number of recurrences to generate. If `None` (default), dates are generated until the recurrence rule is exhausted. :param inc: If `dt` is an instance of the rule and `inc` is `True`, it is included in the output. :yields: Yields a sequence of `datetime` objects. """ if self._cache_complete: gen = self._cache else: gen = self # Select the comparison function if inc: comp = lambda dc, dtc: dc >= dtc else: comp = lambda dc, dtc: dc > dtc # Generate dates n = 0 for d in gen: if comp(d, dt): if count is not None: n += 1 if n > count: break yield d def between(self, after, before, inc=False, count=1): """ Returns all the occurrences of the rrule between after and before. The inc keyword defines what happens if after and/or before are themselves occurrences. With inc=True, they will be included in the list, if they are found in the recurrence set. """ if self._cache_complete: gen = self._cache else: gen = self started = False l = [] if inc: for i in gen: if i > before: break elif not started: if i >= after: started = True l.append(i) else: l.append(i) else: for i in gen: if i >= before: break elif not started: if i > after: started = True l.append(i) else: l.append(i) return l class rrule(rrulebase): """ That's the base of the rrule operation. It accepts all the keywords defined in the RFC as its constructor parameters (except byday, which was renamed to byweekday) and more. The constructor prototype is:: rrule(freq) Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. .. note:: Per RFC section 3.3.10, recurrence instances falling on invalid dates and times are ignored rather than coerced: Recurrence rules may generate recurrence instances with an invalid date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM on a day where the local time is moved forward by an hour at 1:00 AM). Such recurrence instances MUST be ignored and MUST NOT be counted as part of the recurrence set. This can lead to possibly surprising behavior when, for example, the start date occurs at the end of the month: >>> from dateutil.rrule import rrule, MONTHLY >>> from datetime import datetime >>> start_date = datetime(2014, 12, 31) >>> list(rrule(freq=MONTHLY, count=4, dtstart=start_date)) ... # doctest: +NORMALIZE_WHITESPACE [datetime.datetime(2014, 12, 31, 0, 0), datetime.datetime(2015, 1, 31, 0, 0), datetime.datetime(2015, 3, 31, 0, 0), datetime.datetime(2015, 5, 31, 0, 0)] Additionally, it supports the following keyword arguments: :param dtstart: The recurrence start. Besides being the base for the recurrence, missing parameters in the final recurrence instances will also be extracted from this date. If not given, datetime.now() will be used instead. :param interval: The interval between each freq iteration. For example, when using YEARLY, an interval of 2 means once every two years, but with HOURLY, it means once every two hours. The default interval is 1. :param wkst: The week start day. Must be one of the MO, TU, WE constants, or an integer, specifying the first day of the week. This will affect recurrences based on weekly periods. The default week start is got from calendar.firstweekday(), and may be modified by calendar.setfirstweekday(). :param count: How many occurrences will be generated. .. note:: As of version 2.5.0, the use of the ``until`` keyword together with the ``count`` keyword is deprecated per RFC-5545 Sec. 3.3.10. :param until: If given, this must be a datetime instance, that will specify the limit of the recurrence. The last recurrence in the rule is the greatest datetime that is less than or equal to the value specified in the ``until`` parameter. .. note:: As of version 2.5.0, the use of the ``until`` keyword together with the ``count`` keyword is deprecated per RFC-5545 Sec. 3.3.10. :param bysetpos: If given, it must be either an integer, or a sequence of integers, positive or negative. Each given integer will specify an occurrence number, corresponding to the nth occurrence of the rule inside the frequency period. For example, a bysetpos of -1 if combined with a MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will result in the last work day of every month. :param bymonth: If given, it must be either an integer, or a sequence of integers, meaning the months to apply the recurrence to. :param bymonthday: If given, it must be either an integer, or a sequence of integers, meaning the month days to apply the recurrence to. :param byyearday: If given, it must be either an integer, or a sequence of integers, meaning the year days to apply the recurrence to. :param byeaster: If given, it must be either an integer, or a sequence of integers, positive or negative. Each integer will define an offset from the Easter Sunday. Passing the offset 0 to byeaster will yield the Easter Sunday itself. This is an extension to the RFC specification. :param byweekno: If given, it must be either an integer, or a sequence of integers, meaning the week numbers to apply the recurrence to. Week numbers have the meaning described in ISO8601, that is, the first week of the year is that containing at least four days of the new year. :param byweekday: If given, it must be either an integer (0 == MO), a sequence of integers, one of the weekday constants (MO, TU, etc), or a sequence of these constants. When given, these variables will define the weekdays where the recurrence will be applied. It's also possible to use an argument n for the weekday instances, which will mean the nth occurrence of this weekday in the period. For example, with MONTHLY, or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the first friday of the month where the recurrence happens. Notice that in the RFC documentation, this is specified as BYDAY, but was renamed to avoid the ambiguity of that keyword. :param byhour: If given, it must be either an integer, or a sequence of integers, meaning the hours to apply the recurrence to. :param byminute: If given, it must be either an integer, or a sequence of integers, meaning the minutes to apply the recurrence to. :param bysecond: If given, it must be either an integer, or a sequence of integers, meaning the seconds to apply the recurrence to. :param cache: If given, it must be a boolean value specifying to enable or disable caching of results. If you will use the same rrule instance multiple times, enabling caching will improve the performance considerably. """ def __init__(self, freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False): super(rrule, self).__init__(cache) global easter if not dtstart: if until and until.tzinfo: dtstart = datetime.datetime.now(tz=until.tzinfo).replace(microsecond=0) else: dtstart = datetime.datetime.now().replace(microsecond=0) elif not isinstance(dtstart, datetime.datetime): dtstart = datetime.datetime.fromordinal(dtstart.toordinal()) else: dtstart = dtstart.replace(microsecond=0) self._dtstart = dtstart self._tzinfo = dtstart.tzinfo self._freq = freq self._interval = interval self._count = count # Cache the original byxxx rules, if they are provided, as the _byxxx # attributes do not necessarily map to the inputs, and this can be # a problem in generating the strings. Only store things if they've # been supplied (the string retrieval will just use .get()) self._original_rule = {} if until and not isinstance(until, datetime.datetime): until = datetime.datetime.fromordinal(until.toordinal()) self._until = until if self._dtstart and self._until: if (self._dtstart.tzinfo is not None) != (self._until.tzinfo is not None): # According to RFC5545 Section 3.3.10: # https://tools.ietf.org/html/rfc5545#section-3.3.10 # # > If the "DTSTART" property is specified as a date with UTC # > time or a date with local time and time zone reference, # > then the UNTIL rule part MUST be specified as a date with # > UTC time. raise ValueError( 'RRULE UNTIL values must be specified in UTC when DTSTART ' 'is timezone-aware' ) if count is not None and until: warn("Using both 'count' and 'until' is inconsistent with RFC 5545" " and has been deprecated in dateutil. Future versions will " "raise an error.", DeprecationWarning) if wkst is None: self._wkst = calendar.firstweekday() elif isinstance(wkst, integer_types): self._wkst = wkst else: self._wkst = wkst.weekday if bysetpos is None: self._bysetpos = None elif isinstance(bysetpos, integer_types): if bysetpos == 0 or not (-366 <= bysetpos <= 366): raise ValueError("bysetpos must be between 1 and 366, " "or between -366 and -1") self._bysetpos = (bysetpos,) else: self._bysetpos = tuple(bysetpos) for pos in self._bysetpos: if pos == 0 or not (-366 <= pos <= 366): raise ValueError("bysetpos must be between 1 and 366, " "or between -366 and -1") if self._bysetpos: self._original_rule['bysetpos'] = self._bysetpos if (byweekno is None and byyearday is None and bymonthday is None and byweekday is None and byeaster is None): if freq == YEARLY: if bymonth is None: bymonth = dtstart.month self._original_rule['bymonth'] = None bymonthday = dtstart.day self._original_rule['bymonthday'] = None elif freq == MONTHLY: bymonthday = dtstart.day self._original_rule['bymonthday'] = None elif freq == WEEKLY: byweekday = dtstart.weekday() self._original_rule['byweekday'] = None # bymonth if bymonth is None: self._bymonth = None else: if isinstance(bymonth, integer_types): bymonth = (bymonth,) self._bymonth = tuple(sorted(set(bymonth))) if 'bymonth' not in self._original_rule: self._original_rule['bymonth'] = self._bymonth # byyearday if byyearday is None: self._byyearday = None else: if isinstance(byyearday, integer_types): byyearday = (byyearday,) self._byyearday = tuple(sorted(set(byyearday))) self._original_rule['byyearday'] = self._byyearday # byeaster if byeaster is not None: if not easter: from dateutil import easter if isinstance(byeaster, integer_types): self._byeaster = (byeaster,) else: self._byeaster = tuple(sorted(byeaster)) self._original_rule['byeaster'] = self._byeaster else: self._byeaster = None # bymonthday if bymonthday is None: self._bymonthday = () self._bynmonthday = () else: if isinstance(bymonthday, integer_types): bymonthday = (bymonthday,) bymonthday = set(bymonthday) # Ensure it's unique self._bymonthday = tuple(sorted(x for x in bymonthday if x > 0)) self._bynmonthday = tuple(sorted(x for x in bymonthday if x < 0)) # Storing positive numbers first, then negative numbers if 'bymonthday' not in self._original_rule: self._original_rule['bymonthday'] = tuple( itertools.chain(self._bymonthday, self._bynmonthday)) # byweekno if byweekno is None: self._byweekno = None else: if isinstance(byweekno, integer_types): byweekno = (byweekno,) self._byweekno = tuple(sorted(set(byweekno))) self._original_rule['byweekno'] = self._byweekno # byweekday / bynweekday if byweekday is None: self._byweekday = None self._bynweekday = None else: # If it's one of the valid non-sequence types, convert to a # single-element sequence before the iterator that builds the # byweekday set. if isinstance(byweekday, integer_types) or hasattr(byweekday, "n"): byweekday = (byweekday,) self._byweekday = set() self._bynweekday = set() for wday in byweekday: if isinstance(wday, integer_types): self._byweekday.add(wday) elif not wday.n or freq > MONTHLY: self._byweekday.add(wday.weekday) else: self._bynweekday.add((wday.weekday, wday.n)) if not self._byweekday: self._byweekday = None elif not self._bynweekday: self._bynweekday = None if self._byweekday is not None: self._byweekday = tuple(sorted(self._byweekday)) orig_byweekday = [weekday(x) for x in self._byweekday] else: orig_byweekday = () if self._bynweekday is not None: self._bynweekday = tuple(sorted(self._bynweekday)) orig_bynweekday = [weekday(*x) for x in self._bynweekday] else: orig_bynweekday = () if 'byweekday' not in self._original_rule: self._original_rule['byweekday'] = tuple(itertools.chain( orig_byweekday, orig_bynweekday)) # byhour if byhour is None: if freq < HOURLY: self._byhour = {dtstart.hour} else: self._byhour = None else: if isinstance(byhour, integer_types): byhour = (byhour,) if freq == HOURLY: self._byhour = self.__construct_byset(start=dtstart.hour, byxxx=byhour, base=24) else: self._byhour = set(byhour) self._byhour = tuple(sorted(self._byhour)) self._original_rule['byhour'] = self._byhour # byminute if byminute is None: if freq < MINUTELY: self._byminute = {dtstart.minute} else: self._byminute = None else: if isinstance(byminute, integer_types): byminute = (byminute,) if freq == MINUTELY: self._byminute = self.__construct_byset(start=dtstart.minute, byxxx=byminute, base=60) else: self._byminute = set(byminute) self._byminute = tuple(sorted(self._byminute)) self._original_rule['byminute'] = self._byminute # bysecond if bysecond is None: if freq < SECONDLY: self._bysecond = ((dtstart.second,)) else: self._bysecond = None else: if isinstance(bysecond, integer_types): bysecond = (bysecond,) self._bysecond = set(bysecond) if freq == SECONDLY: self._bysecond = self.__construct_byset(start=dtstart.second, byxxx=bysecond, base=60) else: self._bysecond = set(bysecond) self._bysecond = tuple(sorted(self._bysecond)) self._original_rule['bysecond'] = self._bysecond if self._freq >= HOURLY: self._timeset = None else: self._timeset = [] for hour in self._byhour: for minute in self._byminute: for second in self._bysecond: self._timeset.append( datetime.time(hour, minute, second, tzinfo=self._tzinfo)) self._timeset.sort() self._timeset = tuple(self._timeset) def __str__(self): """ Output a string that would generate this RRULE if passed to rrulestr. This is mostly compatible with RFC5545, except for the dateutil-specific extension BYEASTER. """ output = [] h, m, s = [None] * 3 if self._dtstart: output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S')) h, m, s = self._dtstart.timetuple()[3:6] parts = ['FREQ=' + FREQNAMES[self._freq]] if self._interval != 1: parts.append('INTERVAL=' + str(self._interval)) if self._wkst: parts.append('WKST=' + repr(weekday(self._wkst))[0:2]) if self._count is not None: parts.append('COUNT=' + str(self._count)) if self._until: parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S')) if self._original_rule.get('byweekday') is not None: # The str() method on weekday objects doesn't generate # RFC5545-compliant strings, so we should modify that. original_rule = dict(self._original_rule) wday_strings = [] for wday in original_rule['byweekday']: if wday.n: wday_strings.append('{n:+d}{wday}'.format( n=wday.n, wday=repr(wday)[0:2])) else: wday_strings.append(repr(wday)) original_rule['byweekday'] = wday_strings else: original_rule = self._original_rule partfmt = '{name}={vals}' for name, key in [('BYSETPOS', 'bysetpos'), ('BYMONTH', 'bymonth'), ('BYMONTHDAY', 'bymonthday'), ('BYYEARDAY', 'byyearday'), ('BYWEEKNO', 'byweekno'), ('BYDAY', 'byweekday'), ('BYHOUR', 'byhour'), ('BYMINUTE', 'byminute'), ('BYSECOND', 'bysecond'), ('BYEASTER', 'byeaster')]: value = original_rule.get(key) if value: parts.append(partfmt.format(name=name, vals=(','.join(str(v) for v in value)))) output.append('RRULE:' + ';'.join(parts)) return '\n'.join(output) def replace(self, **kwargs): """Return new rrule with same attributes except for those attributes given new values by whichever keyword arguments are specified.""" new_kwargs = {"interval": self._interval, "count": self._count, "dtstart": self._dtstart, "freq": self._freq, "until": self._until, "wkst": self._wkst, "cache": False if self._cache is None else True } new_kwargs.update(self._original_rule) new_kwargs.update(kwargs) return rrule(**new_kwargs) def _iter(self): year, month, day, hour, minute, second, weekday, yearday, _ = \ self._dtstart.timetuple() # Some local variables to speed things up a bit freq = self._freq interval = self._interval wkst = self._wkst until = self._until bymonth = self._bymonth byweekno = self._byweekno byyearday = self._byyearday byweekday = self._byweekday byeaster = self._byeaster bymonthday = self._bymonthday bynmonthday = self._bynmonthday bysetpos = self._bysetpos byhour = self._byhour byminute = self._byminute bysecond = self._bysecond ii = _iterinfo(self) ii.rebuild(year, month) getdayset = {YEARLY: ii.ydayset, MONTHLY: ii.mdayset, WEEKLY: ii.wdayset, DAILY: ii.ddayset, HOURLY: ii.ddayset, MINUTELY: ii.ddayset, SECONDLY: ii.ddayset}[freq] if freq < HOURLY: timeset = self._timeset else: gettimeset = {HOURLY: ii.htimeset, MINUTELY: ii.mtimeset, SECONDLY: ii.stimeset}[freq] if ((freq >= HOURLY and self._byhour and hour not in self._byhour) or (freq >= MINUTELY and self._byminute and minute not in self._byminute) or (freq >= SECONDLY and self._bysecond and second not in self._bysecond)): timeset = () else: timeset = gettimeset(hour, minute, second) total = 0 count = self._count while True: # Get dayset with the right frequency dayset, start, end = getdayset(year, month, day) # Do the "hard" work ;-) filtered = False for i in dayset[start:end]: if ((bymonth and ii.mmask[i] not in bymonth) or (byweekno and not ii.wnomask[i]) or (byweekday and ii.wdaymask[i] not in byweekday) or (ii.nwdaymask and not ii.nwdaymask[i]) or (byeaster and not ii.eastermask[i]) or ((bymonthday or bynmonthday) and ii.mdaymask[i] not in bymonthday and ii.nmdaymask[i] not in bynmonthday) or (byyearday and ((i < ii.yearlen and i+1 not in byyearday and -ii.yearlen+i not in byyearday) or (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and -ii.nextyearlen+i-ii.yearlen not in byyearday)))): dayset[i] = None filtered = True # Output results if bysetpos and timeset: poslist = [] for pos in bysetpos: if pos < 0: daypos, timepos = divmod(pos, len(timeset)) else: daypos, timepos = divmod(pos-1, len(timeset)) try: i = [x for x in dayset[start:end] if x is not None][daypos] time = timeset[timepos] except IndexError: pass else: date = datetime.date.fromordinal(ii.yearordinal+i) res = datetime.datetime.combine(date, time) if res not in poslist: poslist.append(res) poslist.sort() for res in poslist: if until and res > until: self._len = total return elif res >= self._dtstart: if count is not None: count -= 1 if count < 0: self._len = total return total += 1 yield res else: for i in dayset[start:end]: if i is not None: date = datetime.date.fromordinal(ii.yearordinal + i) for time in timeset: res = datetime.datetime.combine(date, time) if until and res > until: self._len = total return elif res >= self._dtstart: if count is not None: count -= 1 if count < 0: self._len = total return total += 1 yield res # Handle frequency and interval fixday = False if freq == YEARLY: year += interval if year > datetime.MAXYEAR: self._len = total return ii.rebuild(year, month) elif freq == MONTHLY: month += interval if month > 12: div, mod = divmod(month, 12) month = mod year += div if month == 0: month = 12 year -= 1 if year > datetime.MAXYEAR: self._len = total return ii.rebuild(year, month) elif freq == WEEKLY: if wkst > weekday: day += -(weekday+1+(6-wkst))+self._interval*7 else: day += -(weekday-wkst)+self._interval*7 weekday = wkst fixday = True elif freq == DAILY: day += interval fixday = True elif freq == HOURLY: if filtered: # Jump to one iteration before next day hour += ((23-hour)//interval)*interval if byhour: ndays, hour = self.__mod_distance(value=hour, byxxx=self._byhour, base=24) else: ndays, hour = divmod(hour+interval, 24) if ndays: day += ndays fixday = True timeset = gettimeset(hour, minute, second) elif freq == MINUTELY: if filtered: # Jump to one iteration before next day minute += ((1439-(hour*60+minute))//interval)*interval valid = False rep_rate = (24*60) for j in range(rep_rate // gcd(interval, rep_rate)): if byminute: nhours, minute = \ self.__mod_distance(value=minute, byxxx=self._byminute, base=60) else: nhours, minute = divmod(minute+interval, 60) div, hour = divmod(hour+nhours, 24) if div: day += div fixday = True filtered = False if not byhour or hour in byhour: valid = True break if not valid: raise ValueError('Invalid combination of interval and ' + 'byhour resulting in empty rule.') timeset = gettimeset(hour, minute, second) elif freq == SECONDLY: if filtered: # Jump to one iteration before next day second += (((86399 - (hour * 3600 + minute * 60 + second)) // interval) * interval) rep_rate = (24 * 3600) valid = False for j in range(0, rep_rate // gcd(interval, rep_rate)): if bysecond: nminutes, second = \ self.__mod_distance(value=second, byxxx=self._bysecond, base=60) else: nminutes, second = divmod(second+interval, 60) div, minute = divmod(minute+nminutes, 60) if div: hour += div div, hour = divmod(hour, 24) if div: day += div fixday = True if ((not byhour or hour in byhour) and (not byminute or minute in byminute) and (not bysecond or second in bysecond)): valid = True break if not valid: raise ValueError('Invalid combination of interval, ' + 'byhour and byminute resulting in empty' + ' rule.') timeset = gettimeset(hour, minute, second) if fixday and day > 28: daysinmonth = calendar.monthrange(year, month)[1] if day > daysinmonth: while day > daysinmonth: day -= daysinmonth month += 1 if month == 13: month = 1 year += 1 if year > datetime.MAXYEAR: self._len = total return daysinmonth = calendar.monthrange(year, month)[1] ii.rebuild(year, month) def __construct_byset(self, start, byxxx, base): """ If a `BYXXX` sequence is passed to the constructor at the same level as `FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some specifications which cannot be reached given some starting conditions. This occurs whenever the interval is not coprime with the base of a given unit and the difference between the starting position and the ending position is not coprime with the greatest common denominator between the interval and the base. For example, with a FREQ of hourly starting at 17:00 and an interval of 4, the only valid values for BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not coprime. :param start: Specifies the starting position. :param byxxx: An iterable containing the list of allowed values. :param base: The largest allowable value for the specified frequency (e.g. 24 hours, 60 minutes). This does not preserve the type of the iterable, returning a set, since the values should be unique and the order is irrelevant, this will speed up later lookups. In the event of an empty set, raises a :exception:`ValueError`, as this results in an empty rrule. """ cset = set() # Support a single byxxx value. if isinstance(byxxx, integer_types): byxxx = (byxxx, ) for num in byxxx: i_gcd = gcd(self._interval, base) # Use divmod rather than % because we need to wrap negative nums. if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0: cset.add(num) if len(cset) == 0: raise ValueError("Invalid rrule byxxx generates an empty set.") return cset def __mod_distance(self, value, byxxx, base): """ Calculates the next value in a sequence where the `FREQ` parameter is specified along with a `BYXXX` parameter at the same "level" (e.g. `HOURLY` specified with `BYHOUR`). :param value: The old value of the component. :param byxxx: The `BYXXX` set, which should have been generated by `rrule._construct_byset`, or something else which checks that a valid rule is present. :param base: The largest allowable value for the specified frequency (e.g. 24 hours, 60 minutes). If a valid value is not found after `base` iterations (the maximum number before the sequence would start to repeat), this raises a :exception:`ValueError`, as no valid values were found. This returns a tuple of `divmod(n*interval, base)`, where `n` is the smallest number of `interval` repetitions until the next specified value in `byxxx` is found. """ accumulator = 0 for ii in range(1, base + 1): # Using divmod() over % to account for negative intervals div, value = divmod(value + self._interval, base) accumulator += div if value in byxxx: return (accumulator, value) class _iterinfo(object): __slots__ = ["rrule", "lastyear", "lastmonth", "yearlen", "nextyearlen", "yearordinal", "yearweekday", "mmask", "mrange", "mdaymask", "nmdaymask", "wdaymask", "wnomask", "nwdaymask", "eastermask"] def __init__(self, rrule): for attr in self.__slots__: setattr(self, attr, None) self.rrule = rrule def rebuild(self, year, month): # Every mask is 7 days longer to handle cross-year weekly periods. rr = self.rrule if year != self.lastyear: self.yearlen = 365 + calendar.isleap(year) self.nextyearlen = 365 + calendar.isleap(year + 1) firstyday = datetime.date(year, 1, 1) self.yearordinal = firstyday.toordinal() self.yearweekday = firstyday.weekday() wday = datetime.date(year, 1, 1).weekday() if self.yearlen == 365: self.mmask = M365MASK self.mdaymask = MDAY365MASK self.nmdaymask = NMDAY365MASK self.wdaymask = WDAYMASK[wday:] self.mrange = M365RANGE else: self.mmask = M366MASK self.mdaymask = MDAY366MASK self.nmdaymask = NMDAY366MASK self.wdaymask = WDAYMASK[wday:] self.mrange = M366RANGE if not rr._byweekno: self.wnomask = None else: self.wnomask = [0]*(self.yearlen+7) # no1wkst = firstwkst = self.wdaymask.index(rr._wkst) no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7 if no1wkst >= 4: no1wkst = 0 # Number of days in the year, plus the days we got # from last year. wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7 else: # Number of days in the year, minus the days we # left in last year. wyearlen = self.yearlen-no1wkst div, mod = divmod(wyearlen, 7) numweeks = div+mod//4 for n in rr._byweekno: if n < 0: n += numweeks+1 if not (0 < n <= numweeks): continue if n > 1: i = no1wkst+(n-1)*7 if no1wkst != firstwkst: i -= 7-firstwkst else: i = no1wkst for j in range(7): self.wnomask[i] = 1 i += 1 if self.wdaymask[i] == rr._wkst: break if 1 in rr._byweekno: # Check week number 1 of next year as well # TODO: Check -numweeks for next year. i = no1wkst+numweeks*7 if no1wkst != firstwkst: i -= 7-firstwkst if i < self.yearlen: # If week starts in next year, we # don't care about it. for j in range(7): self.wnomask[i] = 1 i += 1 if self.wdaymask[i] == rr._wkst: break if no1wkst: # Check last week number of last year as # well. If no1wkst is 0, either the year # started on week start, or week number 1 # got days from last year, so there are no # days from last year's last week number in # this year. if -1 not in rr._byweekno: lyearweekday = datetime.date(year-1, 1, 1).weekday() lno1wkst = (7-lyearweekday+rr._wkst) % 7 lyearlen = 365+calendar.isleap(year-1) if lno1wkst >= 4: lno1wkst = 0 lnumweeks = 52+(lyearlen + (lyearweekday-rr._wkst) % 7) % 7//4 else: lnumweeks = 52+(self.yearlen-no1wkst) % 7//4 else: lnumweeks = -1 if lnumweeks in rr._byweekno: for i in range(no1wkst): self.wnomask[i] = 1 if (rr._bynweekday and (month != self.lastmonth or year != self.lastyear)): ranges = [] if rr._freq == YEARLY: if rr._bymonth: for month in rr._bymonth: ranges.append(self.mrange[month-1:month+1]) else: ranges = [(0, self.yearlen)] elif rr._freq == MONTHLY: ranges = [self.mrange[month-1:month+1]] if ranges: # Weekly frequency won't get here, so we may not # care about cross-year weekly periods. self.nwdaymask = [0]*self.yearlen for first, last in ranges: last -= 1 for wday, n in rr._bynweekday: if n < 0: i = last+(n+1)*7 i -= (self.wdaymask[i]-wday) % 7 else: i = first+(n-1)*7 i += (7-self.wdaymask[i]+wday) % 7 if first <= i <= last: self.nwdaymask[i] = 1 if rr._byeaster: self.eastermask = [0]*(self.yearlen+7) eyday = easter.easter(year).toordinal()-self.yearordinal for offset in rr._byeaster: self.eastermask[eyday+offset] = 1 self.lastyear = year self.lastmonth = month def ydayset(self, year, month, day): return list(range(self.yearlen)), 0, self.yearlen def mdayset(self, year, month, day): dset = [None]*self.yearlen start, end = self.mrange[month-1:month+1] for i in range(start, end): dset[i] = i return dset, start, end def wdayset(self, year, month, day): # We need to handle cross-year weeks here. dset = [None]*(self.yearlen+7) i = datetime.date(year, month, day).toordinal()-self.yearordinal start = i for j in range(7): dset[i] = i i += 1 # if (not (0 <= i < self.yearlen) or # self.wdaymask[i] == self.rrule._wkst): # This will cross the year boundary, if necessary. if self.wdaymask[i] == self.rrule._wkst: break return dset, start, i def ddayset(self, year, month, day): dset = [None] * self.yearlen i = datetime.date(year, month, day).toordinal() - self.yearordinal dset[i] = i return dset, i, i + 1 def htimeset(self, hour, minute, second): tset = [] rr = self.rrule for minute in rr._byminute: for second in rr._bysecond: tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) tset.sort() return tset def mtimeset(self, hour, minute, second): tset = [] rr = self.rrule for second in rr._bysecond: tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) tset.sort() return tset def stimeset(self, hour, minute, second): return (datetime.time(hour, minute, second, tzinfo=self.rrule._tzinfo),) class rruleset(rrulebase): """ The rruleset type allows more complex recurrence setups, mixing multiple rules, dates, exclusion rules, and exclusion dates. The type constructor takes the following keyword arguments: :param cache: If True, caching of results will be enabled, improving performance of multiple queries considerably. """ class _genitem(object): def __init__(self, genlist, gen): try: self.dt = advance_iterator(gen) genlist.append(self) except StopIteration: pass self.genlist = genlist self.gen = gen def __next__(self): try: self.dt = advance_iterator(self.gen) except StopIteration: if self.genlist[0] is self: heapq.heappop(self.genlist) else: self.genlist.remove(self) heapq.heapify(self.genlist) next = __next__ def __lt__(self, other): return self.dt < other.dt def __gt__(self, other): return self.dt > other.dt def __eq__(self, other): return self.dt == other.dt def __ne__(self, other): return self.dt != other.dt def __init__(self, cache=False): super(rruleset, self).__init__(cache) self._rrule = [] self._rdate = [] self._exrule = [] self._exdate = [] @_invalidates_cache def rrule(self, rrule): """ Include the given :py:class:`rrule` instance in the recurrence set generation. """ self._rrule.append(rrule) @_invalidates_cache def rdate(self, rdate): """ Include the given :py:class:`datetime` instance in the recurrence set generation. """ self._rdate.append(rdate) @_invalidates_cache def exrule(self, exrule): """ Include the given rrule instance in the recurrence set exclusion list. Dates which are part of the given recurrence rules will not be generated, even if some inclusive rrule or rdate matches them. """ self._exrule.append(exrule) @_invalidates_cache def exdate(self, exdate): """ Include the given datetime instance in the recurrence set exclusion list. Dates included that way will not be generated, even if some inclusive rrule or rdate matches them. """ self._exdate.append(exdate) def _iter(self): rlist = [] self._rdate.sort() self._genitem(rlist, iter(self._rdate)) for gen in [iter(x) for x in self._rrule]: self._genitem(rlist, gen) exlist = [] self._exdate.sort() self._genitem(exlist, iter(self._exdate)) for gen in [iter(x) for x in self._exrule]: self._genitem(exlist, gen) lastdt = None total = 0 heapq.heapify(rlist) heapq.heapify(exlist) while rlist: ritem = rlist[0] if not lastdt or lastdt != ritem.dt: while exlist and exlist[0] < ritem: exitem = exlist[0] advance_iterator(exitem) if exlist and exlist[0] is exitem: heapq.heapreplace(exlist, exitem) if not exlist or ritem != exlist[0]: total += 1 yield ritem.dt lastdt = ritem.dt advance_iterator(ritem) if rlist and rlist[0] is ritem: heapq.heapreplace(rlist, ritem) self._len = total class _rrulestr(object): _freq_map = {"YEARLY": YEARLY, "MONTHLY": MONTHLY, "WEEKLY": WEEKLY, "DAILY": DAILY, "HOURLY": HOURLY, "MINUTELY": MINUTELY, "SECONDLY": SECONDLY} _weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3, "FR": 4, "SA": 5, "SU": 6} def _handle_int(self, rrkwargs, name, value, **kwargs): rrkwargs[name.lower()] = int(value) def _handle_int_list(self, rrkwargs, name, value, **kwargs): rrkwargs[name.lower()] = [int(x) for x in value.split(',')] _handle_INTERVAL = _handle_int _handle_COUNT = _handle_int _handle_BYSETPOS = _handle_int_list _handle_BYMONTH = _handle_int_list _handle_BYMONTHDAY = _handle_int_list _handle_BYYEARDAY = _handle_int_list _handle_BYEASTER = _handle_int_list _handle_BYWEEKNO = _handle_int_list _handle_BYHOUR = _handle_int_list _handle_BYMINUTE = _handle_int_list _handle_BYSECOND = _handle_int_list def _handle_FREQ(self, rrkwargs, name, value, **kwargs): rrkwargs["freq"] = self._freq_map[value] def _handle_UNTIL(self, rrkwargs, name, value, **kwargs): global parser if not parser: from dateutil import parser try: rrkwargs["until"] = parser.parse(value, ignoretz=kwargs.get("ignoretz"), tzinfos=kwargs.get("tzinfos")) except ValueError: raise ValueError("invalid until date") def _handle_WKST(self, rrkwargs, name, value, **kwargs): rrkwargs["wkst"] = self._weekday_map[value] def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs): """ Two ways to specify this: +1MO or MO(+1) """ l = [] for wday in value.split(','): if '(' in wday: # If it's of the form TH(+1), etc. splt = wday.split('(') w = splt[0] n = int(splt[1][:-1]) elif len(wday): # If it's of the form +1MO for i in range(len(wday)): if wday[i] not in '+-0123456789': break n = wday[:i] or None w = wday[i:] if n: n = int(n) else: raise ValueError("Invalid (empty) BYDAY specification.") l.append(weekdays[self._weekday_map[w]](n)) rrkwargs["byweekday"] = l _handle_BYDAY = _handle_BYWEEKDAY def _parse_rfc_rrule(self, line, dtstart=None, cache=False, ignoretz=False, tzinfos=None): if line.find(':') != -1: name, value = line.split(':') if name != "RRULE": raise ValueError("unknown parameter name") else: value = line rrkwargs = {} for pair in value.split(';'): name, value = pair.split('=') name = name.upper() value = value.upper() try: getattr(self, "_handle_"+name)(rrkwargs, name, value, ignoretz=ignoretz, tzinfos=tzinfos) except AttributeError: raise ValueError("unknown parameter '%s'" % name) except (KeyError, ValueError): raise ValueError("invalid '%s': %s" % (name, value)) return rrule(dtstart=dtstart, cache=cache, **rrkwargs) def _parse_rfc(self, s, dtstart=None, cache=False, unfold=False, forceset=False, compatible=False, ignoretz=False, tzids=None, tzinfos=None): global parser if compatible: forceset = True unfold = True TZID_NAMES = dict(map( lambda x: (x.upper(), x), re.findall('TZID=(?P<name>[^:]+):', s) )) s = s.upper() if not s.strip(): raise ValueError("empty string") if unfold: lines = s.splitlines() i = 0 while i < len(lines): line = lines[i].rstrip() if not line: del lines[i] elif i > 0 and line[0] == " ": lines[i-1] += line[1:] del lines[i] else: i += 1 else: lines = s.split() if (not forceset and len(lines) == 1 and (s.find(':') == -1 or s.startswith('RRULE:'))): return self._parse_rfc_rrule(lines[0], cache=cache, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos) else: rrulevals = [] rdatevals = [] exrulevals = [] exdatevals = [] for line in lines: if not line: continue if line.find(':') == -1: name = "RRULE" value = line else: name, value = line.split(':', 1) parms = name.split(';') if not parms: raise ValueError("empty property name") name = parms[0] parms = parms[1:] if name == "RRULE": for parm in parms: raise ValueError("unsupported RRULE parm: "+parm) rrulevals.append(value) elif name == "RDATE": for parm in parms: if parm != "VALUE=DATE-TIME": raise ValueError("unsupported RDATE parm: "+parm) rdatevals.append(value) elif name == "EXRULE": for parm in parms: raise ValueError("unsupported EXRULE parm: "+parm) exrulevals.append(value) elif name == "EXDATE": for parm in parms: if parm != "VALUE=DATE-TIME": raise ValueError("unsupported EXDATE parm: "+parm) exdatevals.append(value) elif name == "DTSTART": # RFC 5445 3.8.2.4: The VALUE parameter is optional, but # may be found only once. value_found = False TZID = None valid_values = {"VALUE=DATE-TIME", "VALUE=DATE"} for parm in parms: if parm.startswith("TZID="): try: tzkey = TZID_NAMES[parm.split('TZID=')[-1]] except KeyError: continue if tzids is None: from . import tz tzlookup = tz.gettz elif callable(tzids): tzlookup = tzids else: tzlookup = getattr(tzids, 'get', None) if tzlookup is None: msg = ('tzids must be a callable, ' + 'mapping, or None, ' + 'not %s' % tzids) raise ValueError(msg) TZID = tzlookup(tzkey) continue if parm not in valid_values: raise ValueError("unsupported DTSTART parm: "+parm) else: if value_found: msg = ("Duplicate value parameter found in " + "DTSTART: " + parm) raise ValueError(msg) value_found = True if not parser: from dateutil import parser dtstart = parser.parse(value, ignoretz=ignoretz, tzinfos=tzinfos) if TZID is not None: if dtstart.tzinfo is None: dtstart = dtstart.replace(tzinfo=TZID) else: raise ValueError('DTSTART specifies multiple timezones') else: raise ValueError("unsupported property: "+name) if (forceset or len(rrulevals) > 1 or rdatevals or exrulevals or exdatevals): if not parser and (rdatevals or exdatevals): from dateutil import parser rset = rruleset(cache=cache) for value in rrulevals: rset.rrule(self._parse_rfc_rrule(value, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos)) for value in rdatevals: for datestr in value.split(','): rset.rdate(parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos)) for value in exrulevals: rset.exrule(self._parse_rfc_rrule(value, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos)) for value in exdatevals: for datestr in value.split(','): rset.exdate(parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos)) if compatible and dtstart: rset.rdate(dtstart) return rset else: return self._parse_rfc_rrule(rrulevals[0], dtstart=dtstart, cache=cache, ignoretz=ignoretz, tzinfos=tzinfos) def __call__(self, s, **kwargs): return self._parse_rfc(s, **kwargs) rrulestr = _rrulestr() # vim:ts=4:sw=4:et
64,802
37.734608
87
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/__init__.py
# -*- coding: utf-8 -*- try: from ._version import version as __version__ except ImportError: __version__ = 'unknown' __all__ = ['easter', 'parser', 'relativedelta', 'rrule', 'tz', 'utils', 'zoneinfo']
222
23.777778
62
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/_common.py
""" Common code used in multiple modules. """ class weekday(object): __slots__ = ["weekday", "n"] def __init__(self, weekday, n=None): self.weekday = weekday self.n = n def __call__(self, n): if n == self.n: return self else: return self.__class__(self.weekday, n) def __eq__(self, other): try: if self.weekday != other.weekday or self.n != other.n: return False except AttributeError: return False return True def __hash__(self): return hash(( self.weekday, self.n, )) def __ne__(self, other): return not (self == other) def __repr__(self): s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] if not self.n: return s else: return "%s(%+d)" % (s, self.n) # vim:ts=4:sw=4:et
932
20.204545
68
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/zoneinfo/rebuild.py
import logging import os import tempfile import shutil import json from subprocess import check_call from tarfile import TarFile from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* filename is the timezone tarball from ``ftp.iana.org/tz``. """ tmpdir = tempfile.mkdtemp() zonedir = os.path.join(tmpdir, "zoneinfo") moduledir = os.path.dirname(__file__) try: with TarFile.open(filename) as tf: for name in zonegroups: tf.extract(name, tmpdir) filepaths = [os.path.join(tmpdir, n) for n in zonegroups] try: check_call(["zic", "-d", zonedir] + filepaths) except OSError as e: _print_on_nosuchfile(e) raise # write metadata file with open(os.path.join(zonedir, METADATA_FN), 'w') as f: json.dump(metadata, f, indent=4, sort_keys=True) target = os.path.join(moduledir, ZONEFILENAME) with TarFile.open(target, "w:%s" % format) as tf: for entry in os.listdir(zonedir): entrypath = os.path.join(zonedir, entry) tf.add(entrypath, entry) finally: shutil.rmtree(tmpdir) def _print_on_nosuchfile(e): """Print helpful troubleshooting message e is an exception raised by subprocess.check_call() """ if e.errno == 2: logging.error( "Could not find zic. Perhaps you need to install " "libc-bin or some other package that provides it, " "or it's not in your PATH?")
1,719
30.851852
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/zoneinfo/__init__.py
# -*- coding: utf-8 -*- import warnings import json from tarfile import TarFile from pkgutil import get_data from io import BytesIO from dateutil.tz import tzfile as _tzfile __all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"] ZONEFILENAME = "dateutil-zoneinfo.tar.gz" METADATA_FN = 'METADATA' class tzfile(_tzfile): def __reduce__(self): return (gettz, (self._filename,)) def getzoneinfofile_stream(): try: return BytesIO(get_data(__name__, ZONEFILENAME)) except IOError as e: # TODO switch to FileNotFoundError? warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror)) return None class ZoneInfoFile(object): def __init__(self, zonefile_stream=None): if zonefile_stream is not None: with TarFile.open(fileobj=zonefile_stream) as tf: self.zones = {zf.name: tzfile(tf.extractfile(zf), filename=zf.name) for zf in tf.getmembers() if zf.isfile() and zf.name != METADATA_FN} # deal with links: They'll point to their parent object. Less # waste of memory links = {zl.name: self.zones[zl.linkname] for zl in tf.getmembers() if zl.islnk() or zl.issym()} self.zones.update(links) try: metadata_json = tf.extractfile(tf.getmember(METADATA_FN)) metadata_str = metadata_json.read().decode('UTF-8') self.metadata = json.loads(metadata_str) except KeyError: # no metadata in tar file self.metadata = None else: self.zones = {} self.metadata = None def get(self, name, default=None): """ Wrapper for :func:`ZoneInfoFile.zones.get`. This is a convenience method for retrieving zones from the zone dictionary. :param name: The name of the zone to retrieve. (Generally IANA zone names) :param default: The value to return in the event of a missing key. .. versionadded:: 2.6.0 """ return self.zones.get(name, default) # The current API has gettz as a module function, although in fact it taps into # a stateful class. So as a workaround for now, without changing the API, we # will create a new "global" class instance the first time a user requests a # timezone. Ugly, but adheres to the api. # # TODO: Remove after deprecation period. _CLASS_ZONE_INSTANCE = [] def get_zonefile_instance(new_instance=False): """ This is a convenience function which provides a :class:`ZoneInfoFile` instance using the data provided by the ``dateutil`` package. By default, it caches a single instance of the ZoneInfoFile object and returns that. :param new_instance: If ``True``, a new instance of :class:`ZoneInfoFile` is instantiated and used as the cached instance for the next call. Otherwise, new instances are created only as necessary. :return: Returns a :class:`ZoneInfoFile` object. .. versionadded:: 2.6 """ if new_instance: zif = None else: zif = getattr(get_zonefile_instance, '_cached_instance', None) if zif is None: zif = ZoneInfoFile(getzoneinfofile_stream()) get_zonefile_instance._cached_instance = zif return zif def gettz(name): """ This retrieves a time zone from the local zoneinfo tarball that is packaged with dateutil. :param name: An IANA-style time zone name, as found in the zoneinfo file. :return: Returns a :class:`dateutil.tz.tzfile` time zone object. .. warning:: It is generally inadvisable to use this function, and it is only provided for API compatibility with earlier versions. This is *not* equivalent to ``dateutil.tz.gettz()``, which selects an appropriate time zone based on the inputs, favoring system zoneinfo. This is ONLY for accessing the dateutil-specific zoneinfo (which may be out of date compared to the system zoneinfo). .. deprecated:: 2.6 If you need to use a specific zoneinfofile over the system zoneinfo, instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead. Use :func:`get_zonefile_instance` to retrieve an instance of the dateutil-provided zoneinfo. """ warnings.warn("zoneinfo.gettz() will be removed in future versions, " "to use the dateutil-provided zoneinfo files, instantiate a " "ZoneInfoFile object and use ZoneInfoFile.zones.get() " "instead. See the documentation for details.", DeprecationWarning) if len(_CLASS_ZONE_INSTANCE) == 0: _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) return _CLASS_ZONE_INSTANCE[0].zones.get(name) def gettz_db_metadata(): """ Get the zonefile metadata See `zonefile_metadata`_ :returns: A dictionary with the database metadata .. deprecated:: 2.6 See deprecation warning in :func:`zoneinfo.gettz`. To get metadata, query the attribute ``zoneinfo.ZoneInfoFile.metadata``. """ warnings.warn("zoneinfo.gettz_db_metadata() will be removed in future " "versions, to use the dateutil-provided zoneinfo files, " "ZoneInfoFile object and query the 'metadata' attribute " "instead. See the documentation for details.", DeprecationWarning) if len(_CLASS_ZONE_INSTANCE) == 0: _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) return _CLASS_ZONE_INSTANCE[0].metadata
5,889
34.059524
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/parser/_parser.py
# -*- coding: utf-8 -*- """ This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time. This module attempts to be forgiving with regards to unlikely input formats, returning a datetime object even for dates which are ambiguous. If an element of a date/time stamp is omitted, the following rules are applied: - If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is specified. - If a time zone is omitted, a timezone-naive datetime is returned. If any other elements are missing, they are taken from the :class:`datetime.datetime` object passed to the parameter ``default``. If this results in a day number exceeding the valid number of days per month, the value falls back to the end of the month. Additional resources about date/time string formats can be found below: - `A summary of the international standard date and time notation <http://www.cl.cam.ac.uk/~mgk25/iso-time.html>`_ - `W3C Date and Time Formats <http://www.w3.org/TR/NOTE-datetime>`_ - `Time Formats (Planetary Rings Node) <https://pds-rings.seti.org:443/tools/time_formats.html>`_ - `CPAN ParseDate module <http://search.cpan.org/~muir/Time-modules-2013.0912/lib/Time/ParseDate.pm>`_ - `Java SimpleDateFormat Class <https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html>`_ """ from __future__ import unicode_literals import datetime import re import string import time import warnings from calendar import monthrange from io import StringIO import six from six import binary_type, integer_types, text_type from decimal import Decimal from warnings import warn from .. import relativedelta from .. import tz __all__ = ["parse", "parserinfo"] # TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth # making public and/or figuring out if there is something we can # take off their plate. class _timelex(object): # Fractional seconds are sometimes split by a comma _split_decimal = re.compile("([.,])") def __init__(self, instream): if six.PY2: # In Python 2, we can't duck type properly because unicode has # a 'decode' function, and we'd be double-decoding if isinstance(instream, (binary_type, bytearray)): instream = instream.decode() else: if getattr(instream, 'decode', None) is not None: instream = instream.decode() if isinstance(instream, text_type): instream = StringIO(instream) elif getattr(instream, 'read', None) is None: raise TypeError('Parser must be a string or character stream, not ' '{itype}'.format(itype=instream.__class__.__name__)) self.instream = instream self.charstack = [] self.tokenstack = [] self.eof = False def get_token(self): """ This function breaks the time string into lexical units (tokens), which can be parsed by the parser. Lexical units are demarcated by changes in the character set, so any continuous string of letters is considered one unit, any continuous string of numbers is considered one unit. The main complication arises from the fact that dots ('.') can be used both as separators (e.g. "Sep.20.2009") or decimal points (e.g. "4:30:21.447"). As such, it is necessary to read the full context of any dot-separated strings before breaking it into tokens; as such, this function maintains a "token stack", for when the ambiguous context demands that multiple tokens be parsed at once. """ if self.tokenstack: return self.tokenstack.pop(0) seenletters = False token = None state = None while not self.eof: # We only realize that we've reached the end of a token when we # find a character that's not part of the current token - since # that character may be part of the next token, it's stored in the # charstack. if self.charstack: nextchar = self.charstack.pop(0) else: nextchar = self.instream.read(1) while nextchar == '\x00': nextchar = self.instream.read(1) if not nextchar: self.eof = True break elif not state: # First character of the token - determines if we're starting # to parse a word, a number or something else. token = nextchar if self.isword(nextchar): state = 'a' elif self.isnum(nextchar): state = '0' elif self.isspace(nextchar): token = ' ' break # emit token else: break # emit token elif state == 'a': # If we've already started reading a word, we keep reading # letters until we find something that's not part of a word. seenletters = True if self.isword(nextchar): token += nextchar elif nextchar == '.': token += nextchar state = 'a.' else: self.charstack.append(nextchar) break # emit token elif state == '0': # If we've already started reading a number, we keep reading # numbers until we find something that doesn't fit. if self.isnum(nextchar): token += nextchar elif nextchar == '.' or (nextchar == ',' and len(token) >= 2): token += nextchar state = '0.' else: self.charstack.append(nextchar) break # emit token elif state == 'a.': # If we've seen some letters and a dot separator, continue # parsing, and the tokens will be broken up later. seenletters = True if nextchar == '.' or self.isword(nextchar): token += nextchar elif self.isnum(nextchar) and token[-1] == '.': token += nextchar state = '0.' else: self.charstack.append(nextchar) break # emit token elif state == '0.': # If we've seen at least one dot separator, keep going, we'll # break up the tokens later. if nextchar == '.' or self.isnum(nextchar): token += nextchar elif self.isword(nextchar) and token[-1] == '.': token += nextchar state = 'a.' else: self.charstack.append(nextchar) break # emit token if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or token[-1] in '.,')): l = self._split_decimal.split(token) token = l[0] for tok in l[1:]: if tok: self.tokenstack.append(tok) if state == '0.' and token.count('.') == 0: token = token.replace(',', '.') return token def __iter__(self): return self def __next__(self): token = self.get_token() if token is None: raise StopIteration return token def next(self): return self.__next__() # Python 2.x support @classmethod def split(cls, s): return list(cls(s)) @classmethod def isword(cls, nextchar): """ Whether or not the next character is part of a word """ return nextchar.isalpha() @classmethod def isnum(cls, nextchar): """ Whether the next character is part of a number """ return nextchar.isdigit() @classmethod def isspace(cls, nextchar): """ Whether the next character is whitespace """ return nextchar.isspace() class _resultbase(object): def __init__(self): for attr in self.__slots__: setattr(self, attr, None) def _repr(self, classname): l = [] for attr in self.__slots__: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (classname, ", ".join(l)) def __len__(self): return (sum(getattr(self, attr) is not None for attr in self.__slots__)) def __repr__(self): return self._repr(self.__class__.__name__) class parserinfo(object): """ Class which handles what inputs are accepted. Subclass this to customize the language and acceptable values for each parameter. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. Default is ``False``. :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. Default is ``False``. """ # m from a.m/p.m, t from ISO T separator JUMP = [" ", ".", ",", ";", "-", "/", "'", "at", "on", "and", "ad", "m", "t", "of", "st", "nd", "rd", "th"] WEEKDAYS = [("Mon", "Monday"), ("Tue", "Tuesday"), # TODO: "Tues" ("Wed", "Wednesday"), ("Thu", "Thursday"), # TODO: "Thurs" ("Fri", "Friday"), ("Sat", "Saturday"), ("Sun", "Sunday")] MONTHS = [("Jan", "January"), ("Feb", "February"), # TODO: "Febr" ("Mar", "March"), ("Apr", "April"), ("May", "May"), ("Jun", "June"), ("Jul", "July"), ("Aug", "August"), ("Sep", "Sept", "September"), ("Oct", "October"), ("Nov", "November"), ("Dec", "December")] HMS = [("h", "hour", "hours"), ("m", "minute", "minutes"), ("s", "second", "seconds")] AMPM = [("am", "a"), ("pm", "p")] UTCZONE = ["UTC", "GMT", "Z"] PERTAIN = ["of"] TZOFFSET = {} # TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate", # "Anno Domini", "Year of Our Lord"] def __init__(self, dayfirst=False, yearfirst=False): self._jump = self._convert(self.JUMP) self._weekdays = self._convert(self.WEEKDAYS) self._months = self._convert(self.MONTHS) self._hms = self._convert(self.HMS) self._ampm = self._convert(self.AMPM) self._utczone = self._convert(self.UTCZONE) self._pertain = self._convert(self.PERTAIN) self.dayfirst = dayfirst self.yearfirst = yearfirst self._year = time.localtime().tm_year self._century = self._year // 100 * 100 def _convert(self, lst): dct = {} for i, v in enumerate(lst): if isinstance(v, tuple): for v in v: dct[v.lower()] = i else: dct[v.lower()] = i return dct def jump(self, name): return name.lower() in self._jump def weekday(self, name): try: return self._weekdays[name.lower()] except KeyError: pass return None def month(self, name): try: return self._months[name.lower()] + 1 except KeyError: pass return None def hms(self, name): try: return self._hms[name.lower()] except KeyError: return None def ampm(self, name): try: return self._ampm[name.lower()] except KeyError: return None def pertain(self, name): return name.lower() in self._pertain def utczone(self, name): return name.lower() in self._utczone def tzoffset(self, name): if name in self._utczone: return 0 return self.TZOFFSET.get(name) def convertyear(self, year, century_specified=False): """ Converts two-digit years to year within [-50, 49] range of self._year (current local time) """ # Function contract is that the year is always positive assert year >= 0 if year < 100 and not century_specified: # assume current century to start year += self._century if year >= self._year + 50: # if too far in future year -= 100 elif year < self._year - 50: # if too far in past year += 100 return year def validate(self, res): # move to info if res.year is not None: res.year = self.convertyear(res.year, res.century_specified) if res.tzoffset == 0 and not res.tzname or res.tzname == 'Z': res.tzname = "UTC" res.tzoffset = 0 elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname): res.tzoffset = 0 return True class _ymd(list): def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self.century_specified = False self.dstridx = None self.mstridx = None self.ystridx = None @property def has_year(self): return self.ystridx is not None @property def has_month(self): return self.mstridx is not None @property def has_day(self): return self.dstridx is not None def could_be_day(self, value): if self.has_day: return False elif not self.has_month: return 1 <= value <= 31 elif not self.has_year: # Be permissive, assume leapyear month = self[self.mstridx] return 1 <= value <= monthrange(2000, month)[1] else: month = self[self.mstridx] year = self[self.ystridx] return 1 <= value <= monthrange(year, month)[1] def append(self, val, label=None): if hasattr(val, '__len__'): if val.isdigit() and len(val) > 2: self.century_specified = True if label not in [None, 'Y']: # pragma: no cover raise ValueError(label) label = 'Y' elif val > 100: self.century_specified = True if label not in [None, 'Y']: # pragma: no cover raise ValueError(label) label = 'Y' super(self.__class__, self).append(int(val)) if label == 'M': if self.has_month: raise ValueError('Month is already set') self.mstridx = len(self) - 1 elif label == 'D': if self.has_day: raise ValueError('Day is already set') self.dstridx = len(self) - 1 elif label == 'Y': if self.has_year: raise ValueError('Year is already set') self.ystridx = len(self) - 1 def _resolve_from_stridxs(self, strids): """ Try to resolve the identities of year/month/day elements using ystridx, mstridx, and dstridx, if enough of these are specified. """ if len(self) == 3 and len(strids) == 2: # we can back out the remaining stridx value missing = [x for x in range(3) if x not in strids.values()] key = [x for x in ['y', 'm', 'd'] if x not in strids] assert len(missing) == len(key) == 1 key = key[0] val = missing[0] strids[key] = val assert len(self) == len(strids) # otherwise this should not be called out = {key: self[strids[key]] for key in strids} return (out.get('y'), out.get('m'), out.get('d')) def resolve_ymd(self, yearfirst, dayfirst): len_ymd = len(self) year, month, day = (None, None, None) strids = (('y', self.ystridx), ('m', self.mstridx), ('d', self.dstridx)) strids = {key: val for key, val in strids if val is not None} if (len(self) == len(strids) > 0 or (len(self) == 3 and len(strids) == 2)): return self._resolve_from_stridxs(strids) mstridx = self.mstridx if len_ymd > 3: raise ValueError("More than three YMD values") elif len_ymd == 1 or (mstridx is not None and len_ymd == 2): # One member, or two members with a month string if mstridx is not None: month = self[mstridx] # since mstridx is 0 or 1, self[mstridx-1] always # looks up the other element other = self[mstridx - 1] else: other = self[0] if len_ymd > 1 or mstridx is None: if other > 31: year = other else: day = other elif len_ymd == 2: # Two members with numbers if self[0] > 31: # 99-01 year, month = self elif self[1] > 31: # 01-99 month, year = self elif dayfirst and self[1] <= 12: # 13-01 day, month = self else: # 01-13 month, day = self elif len_ymd == 3: # Three members if mstridx == 0: if self[1] > 31: # Apr-2003-25 month, year, day = self else: month, day, year = self elif mstridx == 1: if self[0] > 31 or (yearfirst and self[2] <= 31): # 99-Jan-01 year, month, day = self else: # 01-Jan-01 # Give precendence to day-first, since # two-digit years is usually hand-written. day, month, year = self elif mstridx == 2: # WTF!? if self[1] > 31: # 01-99-Jan day, year, month = self else: # 99-01-Jan year, day, month = self else: if (self[0] > 31 or self.ystridx == 0 or (yearfirst and self[1] <= 12 and self[2] <= 31)): # 99-01-01 if dayfirst and self[2] <= 12: year, day, month = self else: year, month, day = self elif self[0] > 12 or (dayfirst and self[1] <= 12): # 13-01-01 day, month, year = self else: # 01-13-01 month, day, year = self return year, month, day class parser(object): def __init__(self, info=None): self.info = info or parserinfo() def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs): """ Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime.datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param \\*\\*kwargs: Keyword arguments as passed to ``_parse()``. :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ValueError: Raised for invalid or unknown string format, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises TypeError: Raised for non-string or character stream input. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. """ if default is None: default = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) res, skipped_tokens = self._parse(timestr, **kwargs) if res is None: raise ValueError("Unknown string format:", timestr) if len(res) == 0: raise ValueError("String does not contain a date:", timestr) ret = self._build_naive(res, default) if not ignoretz: ret = self._build_tzaware(ret, res, tzinfos) if kwargs.get('fuzzy_with_tokens', False): return ret, skipped_tokens else: return ret class _result(_resultbase): __slots__ = ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond", "tzname", "tzoffset", "ampm","any_unused_tokens"] def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, fuzzy_with_tokens=False): """ Private method which performs the heavy lifting of parsing, called from ``parse()``, which passes on its ``kwargs`` to this function. :param timestr: The string to parse. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. If set to ``None``, this value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. If this is set to ``None``, the value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param fuzzy: Whether to allow fuzzy parsing, allowing for string like "Today is January 1, 2047 at 8:21:00AM". :param fuzzy_with_tokens: If ``True``, ``fuzzy`` is automatically set to True, and the parser will return a tuple where the first element is the parsed :class:`datetime.datetime` datetimestamp and the second element is a tuple containing the portions of the string which were ignored: .. doctest:: >>> from dateutil.parser import parse >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) """ if fuzzy_with_tokens: fuzzy = True info = self.info if dayfirst is None: dayfirst = info.dayfirst if yearfirst is None: yearfirst = info.yearfirst res = self._result() l = _timelex.split(timestr) # Splits the timestr into tokens skipped_idxs = [] # year/month/day list ymd = _ymd() len_l = len(l) i = 0 try: while i < len_l: # Check if it's a number value_repr = l[i] try: value = float(value_repr) except ValueError: value = None if value is not None: # Numeric token i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy) # Check weekday elif info.weekday(l[i]) is not None: value = info.weekday(l[i]) res.weekday = value # Check month name elif info.month(l[i]) is not None: value = info.month(l[i]) ymd.append(value, 'M') if i + 1 < len_l: if l[i + 1] in ('-', '/'): # Jan-01[-99] sep = l[i + 1] ymd.append(l[i + 2]) if i + 3 < len_l and l[i + 3] == sep: # Jan-01-99 ymd.append(l[i + 4]) i += 2 i += 2 elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and info.pertain(l[i + 2])): # Jan of 01 # In this case, 01 is clearly year if l[i + 4].isdigit(): # Convert it here to become unambiguous value = int(l[i + 4]) year = str(info.convertyear(value)) ymd.append(year, 'Y') else: # Wrong guess pass # TODO: not hit in tests i += 4 # Check am/pm elif info.ampm(l[i]) is not None: value = info.ampm(l[i]) val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy) if val_is_ampm: res.hour = self._adjust_ampm(res.hour, value) res.ampm = value elif fuzzy: skipped_idxs.append(i) # Check for a timezone name elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]): res.tzname = l[i] res.tzoffset = info.tzoffset(res.tzname) # Check for something like GMT+3, or BRST+3. Notice # that it doesn't mean "I am 3 hours after GMT", but # "my time +3 is GMT". If found, we reverse the # logic so that timezone parsing code will get it # right. if i + 1 < len_l and l[i + 1] in ('+', '-'): l[i + 1] = ('+', '-')[l[i + 1] == '+'] res.tzoffset = None if info.utczone(res.tzname): # With something like GMT+3, the timezone # is *not* GMT. res.tzname = None # Check for a numbered timezone elif res.hour is not None and l[i] in ('+', '-'): signal = (-1, 1)[l[i] == '+'] len_li = len(l[i + 1]) # TODO: check that l[i + 1] is integer? if len_li == 4: # -0300 hour_offset = int(l[i + 1][:2]) min_offset = int(l[i + 1][2:]) elif i + 2 < len_l and l[i + 2] == ':': # -03:00 hour_offset = int(l[i + 1]) min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like? i += 2 elif len_li <= 2: # -[0]3 hour_offset = int(l[i + 1][:2]) min_offset = 0 else: raise ValueError(timestr) res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60) # Look for a timezone name between parenthesis if (i + 5 < len_l and info.jump(l[i + 2]) and l[i + 3] == '(' and l[i + 5] == ')' and 3 <= len(l[i + 4]) and self._could_be_tzname(res.hour, res.tzname, None, l[i + 4])): # -0300 (BRST) res.tzname = l[i + 4] i += 4 i += 1 # Check jumps elif not (info.jump(l[i]) or fuzzy): raise ValueError(timestr) else: skipped_idxs.append(i) i += 1 # Process year/month/day year, month, day = ymd.resolve_ymd(yearfirst, dayfirst) res.century_specified = ymd.century_specified res.year = year res.month = month res.day = day except (IndexError, ValueError): return None, None if not info.validate(res): return None, None if fuzzy_with_tokens: skipped_tokens = self._recombine_skipped(l, skipped_idxs) return res, tuple(skipped_tokens) else: return res, None def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy): # Token is a number value_repr = tokens[idx] try: value = self._to_decimal(value_repr) except Exception as e: six.raise_from(ValueError('Unknown numeric token'), e) len_li = len(value_repr) len_l = len(tokens) if (len(ymd) == 3 and len_li in (2, 4) and res.hour is None and (idx + 1 >= len_l or (tokens[idx + 1] != ':' and info.hms(tokens[idx + 1]) is None))): # 19990101T23[59] s = tokens[idx] res.hour = int(s[:2]) if len_li == 4: res.minute = int(s[2:]) elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6): # YYMMDD or HHMMSS[.ss] s = tokens[idx] if not ymd and '.' not in tokens[idx]: ymd.append(s[:2]) ymd.append(s[2:4]) ymd.append(s[4:]) else: # 19990101T235959[.59] # TODO: Check if res attributes already set. res.hour = int(s[:2]) res.minute = int(s[2:4]) res.second, res.microsecond = self._parsems(s[4:]) elif len_li in (8, 12, 14): # YYYYMMDD s = tokens[idx] ymd.append(s[:4], 'Y') ymd.append(s[4:6]) ymd.append(s[6:8]) if len_li > 8: res.hour = int(s[8:10]) res.minute = int(s[10:12]) if len_li > 12: res.second = int(s[12:]) elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None: # HH[ ]h or MM[ ]m or SS[.ss][ ]s hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True) (idx, hms) = self._parse_hms(idx, tokens, info, hms_idx) if hms is not None: # TODO: checking that hour/minute/second are not # already set? self._assign_hms(res, value_repr, hms) elif idx + 2 < len_l and tokens[idx + 1] == ':': # HH:MM[:SS[.ss]] res.hour = int(value) value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this? (res.minute, res.second) = self._parse_min_sec(value) if idx + 4 < len_l and tokens[idx + 3] == ':': res.second, res.microsecond = self._parsems(tokens[idx + 4]) idx += 2 idx += 2 elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'): sep = tokens[idx + 1] ymd.append(value_repr) if idx + 2 < len_l and not info.jump(tokens[idx + 2]): if tokens[idx + 2].isdigit(): # 01-01[-01] ymd.append(tokens[idx + 2]) else: # 01-Jan[-01] value = info.month(tokens[idx + 2]) if value is not None: ymd.append(value, 'M') else: raise ValueError() if idx + 3 < len_l and tokens[idx + 3] == sep: # We have three members value = info.month(tokens[idx + 4]) if value is not None: ymd.append(value, 'M') else: ymd.append(tokens[idx + 4]) idx += 2 idx += 1 idx += 1 elif idx + 1 >= len_l or info.jump(tokens[idx + 1]): if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None: # 12 am hour = int(value) res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2])) idx += 1 else: # Year, month or day ymd.append(value) idx += 1 elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24): # 12am hour = int(value) res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1])) idx += 1 elif ymd.could_be_day(value): ymd.append(value) elif not fuzzy: raise ValueError() return idx def _find_hms_idx(self, idx, tokens, info, allow_jump): len_l = len(tokens) if idx+1 < len_l and info.hms(tokens[idx+1]) is not None: # There is an "h", "m", or "s" label following this token. We take # assign the upcoming label to the current token. # e.g. the "12" in 12h" hms_idx = idx + 1 elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and info.hms(tokens[idx+2]) is not None): # There is a space and then an "h", "m", or "s" label. # e.g. the "12" in "12 h" hms_idx = idx + 2 elif idx > 0 and info.hms(tokens[idx-1]) is not None: # There is a "h", "m", or "s" preceeding this token. Since neither # of the previous cases was hit, there is no label following this # token, so we use the previous label. # e.g. the "04" in "12h04" hms_idx = idx-1 elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and info.hms(tokens[idx-2]) is not None): # If we are looking at the final token, we allow for a # backward-looking check to skip over a space. # TODO: Are we sure this is the right condition here? hms_idx = idx - 2 else: hms_idx = None return hms_idx def _assign_hms(self, res, value_repr, hms): # See GH issue #427, fixing float rounding value = self._to_decimal(value_repr) if hms == 0: # Hour res.hour = int(value) if value % 1: res.minute = int(60*(value % 1)) elif hms == 1: (res.minute, res.second) = self._parse_min_sec(value) elif hms == 2: (res.second, res.microsecond) = self._parsems(value_repr) def _could_be_tzname(self, hour, tzname, tzoffset, token): return (hour is not None and tzname is None and tzoffset is None and len(token) <= 5 and all(x in string.ascii_uppercase for x in token)) def _ampm_valid(self, hour, ampm, fuzzy): """ For fuzzy parsing, 'a' or 'am' (both valid English words) may erroneously trigger the AM/PM flag. Deal with that here. """ val_is_ampm = True # If there's already an AM/PM flag, this one isn't one. if fuzzy and ampm is not None: val_is_ampm = False # If AM/PM is found and hour is not, raise a ValueError if hour is None: if fuzzy: val_is_ampm = False else: raise ValueError('No hour specified with AM or PM flag.') elif not 0 <= hour <= 12: # If AM/PM is found, it's a 12 hour clock, so raise # an error for invalid range if fuzzy: val_is_ampm = False else: raise ValueError('Invalid hour specified for 12-hour clock.') return val_is_ampm def _adjust_ampm(self, hour, ampm): if hour < 12 and ampm == 1: hour += 12 elif hour == 12 and ampm == 0: hour = 0 return hour def _parse_min_sec(self, value): # TODO: Every usage of this function sets res.second to the return # value. Are there any cases where second will be returned as None and # we *dont* want to set res.second = None? minute = int(value) second = None sec_remainder = value % 1 if sec_remainder: second = int(60 * sec_remainder) return (minute, second) def _parsems(self, value): """Parse a I[.F] seconds value into (seconds, microseconds).""" if "." not in value: return int(value), 0 else: i, f = value.split(".") return int(i), int(f.ljust(6, "0")[:6]) def _parse_hms(self, idx, tokens, info, hms_idx): # TODO: Is this going to admit a lot of false-positives for when we # just happen to have digits and "h", "m" or "s" characters in non-date # text? I guess hex hashes won't have that problem, but there's plenty # of random junk out there. if hms_idx is None: hms = None new_idx = idx elif hms_idx > idx: hms = info.hms(tokens[hms_idx]) new_idx = hms_idx else: # Looking backwards, increment one. hms = info.hms(tokens[hms_idx]) + 1 new_idx = idx return (new_idx, hms) def _recombine_skipped(self, tokens, skipped_idxs): """ >>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"] >>> skipped_idxs = [0, 1, 2, 5] >>> _recombine_skipped(tokens, skipped_idxs) ["foo bar", "baz"] """ skipped_tokens = [] for i, idx in enumerate(sorted(skipped_idxs)): if i > 0 and idx - 1 == skipped_idxs[i - 1]: skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx] else: skipped_tokens.append(tokens[idx]) return skipped_tokens def _build_tzinfo(self, tzinfos, tzname, tzoffset): if callable(tzinfos): tzdata = tzinfos(tzname, tzoffset) else: tzdata = tzinfos.get(tzname) # handle case where tzinfo is paased an options that returns None # eg tzinfos = {'BRST' : None} if isinstance(tzdata, datetime.tzinfo) or tzdata is None: tzinfo = tzdata elif isinstance(tzdata, text_type): tzinfo = tz.tzstr(tzdata) elif isinstance(tzdata, integer_types): tzinfo = tz.tzoffset(tzname, tzdata) return tzinfo def _build_tzaware(self, naive, res, tzinfos): if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)): tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset) aware = naive.replace(tzinfo=tzinfo) aware = self._assign_tzname(aware, res.tzname) elif res.tzname and res.tzname in time.tzname: aware = naive.replace(tzinfo=tz.tzlocal()) # Handle ambiguous local datetime aware = self._assign_tzname(aware, res.tzname) # This is mostly relevant for winter GMT zones parsed in the UK if (aware.tzname() != res.tzname and res.tzname in self.info.UTCZONE): aware = aware.replace(tzinfo=tz.tzutc()) elif res.tzoffset == 0: aware = naive.replace(tzinfo=tz.tzutc()) elif res.tzoffset: aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset)) elif not res.tzname and not res.tzoffset: # i.e. no timezone information was found. aware = naive elif res.tzname: # tz-like string was parsed but we don't know what to do # with it warnings.warn("tzname {tzname} identified but not understood. " "Pass `tzinfos` argument in order to correctly " "return a timezone-aware datetime. In a future " "version, this will raise an " "exception.".format(tzname=res.tzname), category=UnknownTimezoneWarning) aware = naive return aware def _build_naive(self, res, default): repl = {} for attr in ("year", "month", "day", "hour", "minute", "second", "microsecond"): value = getattr(res, attr) if value is not None: repl[attr] = value if 'day' not in repl: # If the default day exceeds the last day of the month, fall back # to the end of the month. cyear = default.year if res.year is None else res.year cmonth = default.month if res.month is None else res.month cday = default.day if res.day is None else res.day if cday > monthrange(cyear, cmonth)[1]: repl['day'] = monthrange(cyear, cmonth)[1] naive = default.replace(**repl) if res.weekday is not None and not res.day: naive = naive + relativedelta.relativedelta(weekday=res.weekday) return naive def _assign_tzname(self, dt, tzname): if dt.tzname() != tzname: new_dt = tz.enfold(dt, fold=1) if new_dt.tzname() == tzname: return new_dt return dt def _to_decimal(self, val): try: decimal_value = Decimal(val) # See GH 662, edge case, infinite value should not be converted via `_to_decimal` if not decimal_value.is_finite(): raise ValueError("Converted decimal value is infinite or NaN") except Exception as e: msg = "Could not convert %s to decimal" % val six.raise_from(ValueError(msg), e) else: return decimal_value DEFAULTPARSER = parser() def parse(timestr, parserinfo=None, **kwargs): """ Parse a string in one of the supported formats, using the ``parserinfo`` parameters. :param timestr: A string containing a date/time stamp. :param parserinfo: A :class:`parserinfo` object containing parameters for the parser. If ``None``, the default arguments to the :class:`parserinfo` constructor are used. The ``**kwargs`` parameter takes the following keyword arguments: :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. :param ignoretz: If set ``True``, time zones in parsed strings are ignored and a naive :class:`datetime` object is returned. :param tzinfos: Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (``tzname`` and ``tzoffset``) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a :class:`tzinfo` object. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) This parameter is ignored if ``ignoretz`` is set. :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day (``True``) or month (``False``). If ``yearfirst`` is set to ``True``, this distinguishes between YDM and YMD. If set to ``None``, this value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If ``True``, the first number is taken to be the year, otherwise the last number is taken to be the year. If this is set to ``None``, the value is retrieved from the current :class:`parserinfo` object (which itself defaults to ``False``). :param fuzzy: Whether to allow fuzzy parsing, allowing for string like "Today is January 1, 2047 at 8:21:00AM". :param fuzzy_with_tokens: If ``True``, ``fuzzy`` is automatically set to True, and the parser will return a tuple where the first element is the parsed :class:`datetime.datetime` datetimestamp and the second element is a tuple containing the portions of the string which were ignored: .. doctest:: >>> from dateutil.parser import parse >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) :return: Returns a :class:`datetime.datetime` object or, if the ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the first element being a :class:`datetime.datetime` object, the second a tuple containing the fuzzy tokens. :raises ValueError: Raised for invalid or unknown string format, if the provided :class:`tzinfo` is not in a valid format, or if an invalid date would be created. :raises OverflowError: Raised if the parsed date exceeds the largest valid C integer on your system. """ if parserinfo: return parser(parserinfo).parse(timestr, **kwargs) else: return DEFAULTPARSER.parse(timestr, **kwargs) class _tzparser(object): class _result(_resultbase): __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", "start", "end"] class _attr(_resultbase): __slots__ = ["month", "week", "weekday", "yday", "jyday", "day", "time"] def __repr__(self): return self._repr("") def __init__(self): _resultbase.__init__(self) self.start = self._attr() self.end = self._attr() def parse(self, tzstr): res = self._result() l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x] used_idxs = list() try: len_l = len(l) i = 0 while i < len_l: # BRST+3[BRDT[+2]] j = i while j < len_l and not [x for x in l[j] if x in "0123456789:,-+"]: j += 1 if j != i: if not res.stdabbr: offattr = "stdoffset" res.stdabbr = "".join(l[i:j]) else: offattr = "dstoffset" res.dstabbr = "".join(l[i:j]) for ii in range(j): used_idxs.append(ii) i = j if (i < len_l and (l[i] in ('+', '-') or l[i][0] in "0123456789")): if l[i] in ('+', '-'): # Yes, that's right. See the TZ variable # documentation. signal = (1, -1)[l[i] == '+'] used_idxs.append(i) i += 1 else: signal = -1 len_li = len(l[i]) if len_li == 4: # -0300 setattr(res, offattr, (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60) * signal) elif i + 1 < len_l and l[i + 1] == ':': # -03:00 setattr(res, offattr, (int(l[i]) * 3600 + int(l[i + 2]) * 60) * signal) used_idxs.append(i) i += 2 elif len_li <= 2: # -[0]3 setattr(res, offattr, int(l[i][:2]) * 3600 * signal) else: return None used_idxs.append(i) i += 1 if res.dstabbr: break else: break if i < len_l: for j in range(i, len_l): if l[j] == ';': l[j] = ',' assert l[i] == ',' i += 1 if i >= len_l: pass elif (8 <= l.count(',') <= 9 and not [y for x in l[i:] if x != ',' for y in x if y not in "0123456789+-"]): # GMT0BST,3,0,30,3600,10,0,26,7200[,3600] for x in (res.start, res.end): x.month = int(l[i]) used_idxs.append(i) i += 2 if l[i] == '-': value = int(l[i + 1]) * -1 used_idxs.append(i) i += 1 else: value = int(l[i]) used_idxs.append(i) i += 2 if value: x.week = value x.weekday = (int(l[i]) - 1) % 7 else: x.day = int(l[i]) used_idxs.append(i) i += 2 x.time = int(l[i]) used_idxs.append(i) i += 2 if i < len_l: if l[i] in ('-', '+'): signal = (-1, 1)[l[i] == "+"] used_idxs.append(i) i += 1 else: signal = 1 used_idxs.append(i) res.dstoffset = (res.stdoffset + int(l[i]) * signal) # This was a made-up format that is not in normal use warn(('Parsed time zone "%s"' % tzstr) + 'is in a non-standard dateutil-specific format, which ' + 'is now deprecated; support for parsing this format ' + 'will be removed in future versions. It is recommended ' + 'that you switch to a standard format like the GNU ' + 'TZ variable format.', tz.DeprecatedTzFormatWarning) elif (l.count(',') == 2 and l[i:].count('/') <= 2 and not [y for x in l[i:] if x not in (',', '/', 'J', 'M', '.', '-', ':') for y in x if y not in "0123456789"]): for x in (res.start, res.end): if l[i] == 'J': # non-leap year day (1 based) used_idxs.append(i) i += 1 x.jyday = int(l[i]) elif l[i] == 'M': # month[-.]week[-.]weekday used_idxs.append(i) i += 1 x.month = int(l[i]) used_idxs.append(i) i += 1 assert l[i] in ('-', '.') used_idxs.append(i) i += 1 x.week = int(l[i]) if x.week == 5: x.week = -1 used_idxs.append(i) i += 1 assert l[i] in ('-', '.') used_idxs.append(i) i += 1 x.weekday = (int(l[i]) - 1) % 7 else: # year day (zero based) x.yday = int(l[i]) + 1 used_idxs.append(i) i += 1 if i < len_l and l[i] == '/': used_idxs.append(i) i += 1 # start time len_li = len(l[i]) if len_li == 4: # -0300 x.time = (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60) elif i + 1 < len_l and l[i + 1] == ':': # -03:00 x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60 used_idxs.append(i) i += 2 if i + 1 < len_l and l[i + 1] == ':': used_idxs.append(i) i += 2 x.time += int(l[i]) elif len_li <= 2: # -[0]3 x.time = (int(l[i][:2]) * 3600) else: return None used_idxs.append(i) i += 1 assert i == len_l or l[i] == ',' i += 1 assert i >= len_l except (IndexError, ValueError, AssertionError): return None unused_idxs = set(range(len_l)).difference(used_idxs) res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"}) return res DEFAULTTZPARSER = _tzparser() def _parsetz(tzstr): return DEFAULTTZPARSER.parse(tzstr) class UnknownTimezoneWarning(RuntimeWarning): """Raised when the parser finds a timezone it cannot parse into a tzinfo""" # vim:ts=4:sw=4:et
57,607
35.483851
97
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/parser/isoparser.py
# -*- coding: utf-8 -*- """ This module offers a parser for ISO-8601 strings It is intended to support all valid date, time and datetime formats per the ISO-8601 specification. ..versionadded:: 2.7.0 """ from datetime import datetime, timedelta, time, date import calendar from dateutil import tz from functools import wraps import re import six __all__ = ["isoparse", "isoparser"] def _takes_ascii(f): @wraps(f) def func(self, str_in, *args, **kwargs): # If it's a stream, read the whole thing str_in = getattr(str_in, 'read', lambda: str_in)() # If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII if isinstance(str_in, six.text_type): # ASCII is the same in UTF-8 try: str_in = str_in.encode('ascii') except UnicodeEncodeError as e: msg = 'ISO-8601 strings should contain only ASCII characters' six.raise_from(ValueError(msg), e) return f(self, str_in, *args, **kwargs) return func class isoparser(object): def __init__(self, sep=None): """ :param sep: A single character that separates date and time portions. If ``None``, the parser will accept any single character. For strict ISO-8601 adherence, pass ``'T'``. """ if sep is not None: if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'): raise ValueError('Separator must be a single, non-numeric ' + 'ASCII character') sep = sep.encode('ascii') self._sep = sep @_takes_ascii def isoparse(self, dt_str): """ Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. An ISO-8601 datetime string consists of a date portion, followed optionally by a time portion - the date and time portions are separated by a single character separator, which is ``T`` in the official standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be combined with a time portion. Supported date formats are: Common: - ``YYYY`` - ``YYYY-MM`` or ``YYYYMM`` - ``YYYY-MM-DD`` or ``YYYYMMDD`` Uncommon: - ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0) - ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day The ISO week and day numbering follows the same logic as :func:`datetime.date.isocalendar`. Supported time formats are: - ``hh`` - ``hh:mm`` or ``hhmm`` - ``hh:mm:ss`` or ``hhmmss`` - ``hh:mm:ss.sss`` or ``hh:mm:ss.ssssss`` (3-6 sub-second digits) Midnight is a special case for `hh`, as the standard supports both 00:00 and 24:00 as a representation. .. caution:: Support for fractional components other than seconds is part of the ISO-8601 standard, but is not currently implemented in this parser. Supported time zone offset formats are: - `Z` (UTC) - `±HH:MM` - `±HHMM` - `±HH` Offsets will be represented as :class:`dateutil.tz.tzoffset` objects, with the exception of UTC, which will be represented as :class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`. :param dt_str: A string or stream containing only an ISO-8601 datetime string :return: Returns a :class:`datetime.datetime` representing the string. Unspecified components default to their lowest value. .. warning:: As of version 2.7.0, the strictness of the parser should not be considered a stable part of the contract. Any valid ISO-8601 string that parses correctly with the default settings will continue to parse correctly in future versions, but invalid strings that currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not guaranteed to continue failing in future versions if they encode a valid date. .. versionadded:: 2.7.0 """ components, pos = self._parse_isodate(dt_str) if len(dt_str) > pos: if self._sep is None or dt_str[pos:pos + 1] == self._sep: components += self._parse_isotime(dt_str[pos + 1:]) else: raise ValueError('String contains unknown ISO components') return datetime(*components) @_takes_ascii def parse_isodate(self, datestr): """ Parse the date portion of an ISO string. :param datestr: The string portion of an ISO string, without a separator :return: Returns a :class:`datetime.date` object """ components, pos = self._parse_isodate(datestr) if pos < len(datestr): raise ValueError('String contains unknown ISO ' + 'components: {}'.format(datestr)) return date(*components) @_takes_ascii def parse_isotime(self, timestr): """ Parse the time portion of an ISO string. :param timestr: The time portion of an ISO string, without a separator :return: Returns a :class:`datetime.time` object """ return time(*self._parse_isotime(timestr)) @_takes_ascii def parse_tzstr(self, tzstr, zero_as_utc=True): """ Parse a valid ISO time zone string. See :func:`isoparser.isoparse` for details on supported formats. :param tzstr: A string representing an ISO time zone offset :param zero_as_utc: Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones :return: Returns :class:`dateutil.tz.tzoffset` for offsets and :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is specified) offsets equivalent to UTC. """ return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) # Constants _MICROSECOND_END_REGEX = re.compile(b'[-+Z]+') _DATE_SEP = b'-' _TIME_SEP = b':' _MICRO_SEP = b'.' def _parse_isodate(self, dt_str): try: return self._parse_isodate_common(dt_str) except ValueError: return self._parse_isodate_uncommon(dt_str) def _parse_isodate_common(self, dt_str): len_str = len(dt_str) components = [1, 1, 1] if len_str < 4: raise ValueError('ISO string too short') # Year components[0] = int(dt_str[0:4]) pos = 4 if pos >= len_str: return components, pos has_sep = dt_str[pos:pos + 1] == self._DATE_SEP if has_sep: pos += 1 # Month if len_str - pos < 2: raise ValueError('Invalid common month') components[1] = int(dt_str[pos:pos + 2]) pos += 2 if pos >= len_str: if has_sep: return components, pos else: raise ValueError('Invalid ISO format') if has_sep: if dt_str[pos:pos + 1] != self._DATE_SEP: raise ValueError('Invalid separator in ISO string') pos += 1 # Day if len_str - pos < 2: raise ValueError('Invalid common day') components[2] = int(dt_str[pos:pos + 2]) return components, pos + 2 def _parse_isodate_uncommon(self, dt_str): if len(dt_str) < 4: raise ValueError('ISO string too short') # All ISO formats start with the year year = int(dt_str[0:4]) has_sep = dt_str[4:5] == self._DATE_SEP pos = 4 + has_sep # Skip '-' if it's there if dt_str[pos:pos + 1] == b'W': # YYYY-?Www-?D? pos += 1 weekno = int(dt_str[pos:pos + 2]) pos += 2 dayno = 1 if len(dt_str) > pos: if (dt_str[pos:pos + 1] == self._DATE_SEP) != has_sep: raise ValueError('Inconsistent use of dash separator') pos += has_sep dayno = int(dt_str[pos:pos + 1]) pos += 1 base_date = self._calculate_weekdate(year, weekno, dayno) else: # YYYYDDD or YYYY-DDD if len(dt_str) - pos < 3: raise ValueError('Invalid ordinal day') ordinal_day = int(dt_str[pos:pos + 3]) pos += 3 if ordinal_day < 1 or ordinal_day > (365 + calendar.isleap(year)): raise ValueError('Invalid ordinal day' + ' {} for year {}'.format(ordinal_day, year)) base_date = date(year, 1, 1) + timedelta(days=ordinal_day - 1) components = [base_date.year, base_date.month, base_date.day] return components, pos def _calculate_weekdate(self, year, week, day): """ Calculate the day of corresponding to the ISO year-week-day calendar. This function is effectively the inverse of :func:`datetime.date.isocalendar`. :param year: The year in the ISO calendar :param week: The week in the ISO calendar - range is [1, 53] :param day: The day in the ISO calendar - range is [1 (MON), 7 (SUN)] :return: Returns a :class:`datetime.date` """ if not 0 < week < 54: raise ValueError('Invalid week: {}'.format(week)) if not 0 < day < 8: # Range is 1-7 raise ValueError('Invalid weekday: {}'.format(day)) # Get week 1 for the specific year: jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1) # Now add the specific number of weeks and days to get what we want week_offset = (week - 1) * 7 + (day - 1) return week_1 + timedelta(days=week_offset) def _parse_isotime(self, timestr): len_str = len(timestr) components = [0, 0, 0, 0, None] pos = 0 comp = -1 if len(timestr) < 2: raise ValueError('ISO time too short') has_sep = len_str >= 3 and timestr[2:3] == self._TIME_SEP while pos < len_str and comp < 5: comp += 1 if timestr[pos:pos + 1] in b'-+Z': # Detect time zone boundary components[-1] = self._parse_tzstr(timestr[pos:]) pos = len_str break if comp < 3: # Hour, minute, second components[comp] = int(timestr[pos:pos + 2]) pos += 2 if (has_sep and pos < len_str and timestr[pos:pos + 1] == self._TIME_SEP): pos += 1 if comp == 3: # Microsecond if timestr[pos:pos + 1] != self._MICRO_SEP: continue pos += 1 us_str = self._MICROSECOND_END_REGEX.split(timestr[pos:pos + 6], 1)[0] components[comp] = int(us_str) * 10**(6 - len(us_str)) pos += len(us_str) if pos < len_str: raise ValueError('Unused components in ISO string') if components[0] == 24: # Standard supports 00:00 and 24:00 as representations of midnight if any(component != 0 for component in components[1:4]): raise ValueError('Hour may only be 24 at 24:00:00.000') components[0] = 0 return components def _parse_tzstr(self, tzstr, zero_as_utc=True): if tzstr == b'Z': return tz.tzutc() if len(tzstr) not in {3, 5, 6}: raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters') if tzstr[0:1] == b'-': mult = -1 elif tzstr[0:1] == b'+': mult = 1 else: raise ValueError('Time zone offset requires sign') hours = int(tzstr[1:3]) if len(tzstr) == 3: minutes = 0 else: minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):]) if zero_as_utc and hours == 0 and minutes == 0: return tz.tzutc() else: if minutes > 59: raise ValueError('Invalid minutes in time zone offset') if hours > 23: raise ValueError('Invalid hours in time zone offset') return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) DEFAULT_ISOPARSER = isoparser() isoparse = DEFAULT_ISOPARSER.isoparse
12,899
30.695332
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/parser/__init__.py
# -*- coding: utf-8 -*- from ._parser import parse, parser, parserinfo from ._parser import DEFAULTPARSER, DEFAULTTZPARSER from ._parser import UnknownTimezoneWarning from ._parser import __doc__ from .isoparser import isoparser, isoparse __all__ = ['parse', 'parser', 'parserinfo', 'isoparse', 'isoparser', 'UnknownTimezoneWarning'] ### # Deprecate portions of the private interface so that downstream code that # is improperly relying on it is given *some* notice. def __deprecated_private_func(f): from functools import wraps import warnings msg = ('{name} is a private function and may break without warning, ' 'it will be moved and or renamed in future versions.') msg = msg.format(name=f.__name__) @wraps(f) def deprecated_func(*args, **kwargs): warnings.warn(msg, DeprecationWarning) return f(*args, **kwargs) return deprecated_func def __deprecate_private_class(c): import warnings msg = ('{name} is a private class and may break without warning, ' 'it will be moved and or renamed in future versions.') msg = msg.format(name=c.__name__) class private_class(c): __doc__ = c.__doc__ def __init__(self, *args, **kwargs): warnings.warn(msg, DeprecationWarning) super(private_class, self).__init__(*args, **kwargs) private_class.__name__ = c.__name__ return private_class from ._parser import _timelex, _resultbase from ._parser import _tzparser, _parsetz _timelex = __deprecate_private_class(_timelex) _tzparser = __deprecate_private_class(_tzparser) _resultbase = __deprecate_private_class(_resultbase) _parsetz = __deprecated_private_func(_parsetz)
1,727
27.327869
74
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/tz/_factories.py
from datetime import timedelta class _TzSingleton(type): def __init__(cls, *args, **kwargs): cls.__instance = None super(_TzSingleton, cls).__init__(*args, **kwargs) def __call__(cls): if cls.__instance is None: cls.__instance = super(_TzSingleton, cls).__call__() return cls.__instance class _TzFactory(type): def instance(cls, *args, **kwargs): """Alternate constructor that returns a fresh instance""" return type.__call__(cls, *args, **kwargs) class _TzOffsetFactory(_TzFactory): def __init__(cls, *args, **kwargs): cls.__instances = {} def __call__(cls, name, offset): if isinstance(offset, timedelta): key = (name, offset.total_seconds()) else: key = (name, offset) instance = cls.__instances.get(key, None) if instance is None: instance = cls.__instances.setdefault(key, cls.instance(name, offset)) return instance class _TzStrFactory(_TzFactory): def __init__(cls, *args, **kwargs): cls.__instances = {} def __call__(cls, s, posix_offset=False): key = (s, posix_offset) instance = cls.__instances.get(key, None) if instance is None: instance = cls.__instances.setdefault(key, cls.instance(s, posix_offset)) return instance
1,434
27.7
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/tz/win.py
# This code was originally contributed by Jeffrey Harris. import datetime import struct from six.moves import winreg from six import text_type try: import ctypes from ctypes import wintypes except ValueError: # ValueError is raised on non-Windows systems for some horrible reason. raise ImportError("Running tzwin on non-Windows system") from ._common import tzrangebase __all__ = ["tzwin", "tzwinlocal", "tzres"] ONEWEEK = datetime.timedelta(7) TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones" TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones" TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation" def _settzkeyname(): handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: winreg.OpenKey(handle, TZKEYNAMENT).Close() TZKEYNAME = TZKEYNAMENT except WindowsError: TZKEYNAME = TZKEYNAME9X handle.Close() return TZKEYNAME TZKEYNAME = _settzkeyname() class tzres(object): """ Class for accessing `tzres.dll`, which contains timezone name related resources. .. versionadded:: 2.5.0 """ p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char def __init__(self, tzres_loc='tzres.dll'): # Load the user32 DLL so we can load strings from tzres user32 = ctypes.WinDLL('user32') # Specify the LoadStringW function user32.LoadStringW.argtypes = (wintypes.HINSTANCE, wintypes.UINT, wintypes.LPWSTR, ctypes.c_int) self.LoadStringW = user32.LoadStringW self._tzres = ctypes.WinDLL(tzres_loc) self.tzres_loc = tzres_loc def load_name(self, offset): """ Load a timezone name from a DLL offset (integer). >>> from dateutil.tzwin import tzres >>> tzr = tzres() >>> print(tzr.load_name(112)) 'Eastern Standard Time' :param offset: A positive integer value referring to a string from the tzres dll. ..note: Offsets found in the registry are generally of the form `@tzres.dll,-114`. The offset in this case if 114, not -114. """ resource = self.p_wchar() lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR) nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0) return resource[:nchar] def name_from_string(self, tzname_str): """ Parse strings as returned from the Windows registry into the time zone name as defined in the registry. >>> from dateutil.tzwin import tzres >>> tzr = tzres() >>> print(tzr.name_from_string('@tzres.dll,-251')) 'Dateline Daylight Time' >>> print(tzr.name_from_string('Eastern Standard Time')) 'Eastern Standard Time' :param tzname_str: A timezone name string as returned from a Windows registry key. :return: Returns the localized timezone string from tzres.dll if the string is of the form `@tzres.dll,-offset`, else returns the input string. """ if not tzname_str.startswith('@'): return tzname_str name_splt = tzname_str.split(',-') try: offset = int(name_splt[1]) except: raise ValueError("Malformed timezone string.") return self.load_name(offset) class tzwinbase(tzrangebase): """tzinfo class based on win32's timezones available in the registry.""" def __init__(self): raise NotImplementedError('tzwinbase is an abstract base class') def __eq__(self, other): # Compare on all relevant dimensions, including name. if not isinstance(other, tzwinbase): return NotImplemented return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and self._stddayofweek == other._stddayofweek and self._dstdayofweek == other._dstdayofweek and self._stdweeknumber == other._stdweeknumber and self._dstweeknumber == other._dstweeknumber and self._stdhour == other._stdhour and self._dsthour == other._dsthour and self._stdminute == other._stdminute and self._dstminute == other._dstminute and self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr) @staticmethod def list(): """Return a list of all time zones known to the system.""" with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: with winreg.OpenKey(handle, TZKEYNAME) as tzkey: result = [winreg.EnumKey(tzkey, i) for i in range(winreg.QueryInfoKey(tzkey)[0])] return result def display(self): return self._display def transitions(self, year): """ For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. :return: Returns a :class:`tuple` of :class:`datetime.datetime` objects, ``(dston, dstoff)`` for zones with an annual DST transition, or ``None`` for fixed offset zones. """ if not self.hasdst: return None dston = picknthweekday(year, self._dstmonth, self._dstdayofweek, self._dsthour, self._dstminute, self._dstweeknumber) dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek, self._stdhour, self._stdminute, self._stdweeknumber) # Ambiguous dates default to the STD side dstoff -= self._dst_base_offset return dston, dstoff def _get_hasdst(self): return self._dstmonth != 0 @property def _dst_base_offset(self): return self._dst_base_offset_ class tzwin(tzwinbase): def __init__(self, name): self._name = name with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: tzkeyname = text_type("{kn}\\{name}").format(kn=TZKEYNAME, name=name) with winreg.OpenKey(handle, tzkeyname) as tzkey: keydict = valuestodict(tzkey) self._std_abbr = keydict["Std"] self._dst_abbr = keydict["Dlt"] self._display = keydict["Display"] # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm tup = struct.unpack("=3l16h", keydict["TZI"]) stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1 dstoffset = stdoffset-tup[2] # + DaylightBias * -1 self._std_offset = datetime.timedelta(minutes=stdoffset) self._dst_offset = datetime.timedelta(minutes=dstoffset) # for the meaning see the win32 TIME_ZONE_INFORMATION structure docs # http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx (self._stdmonth, self._stddayofweek, # Sunday = 0 self._stdweeknumber, # Last = 5 self._stdhour, self._stdminute) = tup[4:9] (self._dstmonth, self._dstdayofweek, # Sunday = 0 self._dstweeknumber, # Last = 5 self._dsthour, self._dstminute) = tup[12:17] self._dst_base_offset_ = self._dst_offset - self._std_offset self.hasdst = self._get_hasdst() def __repr__(self): return "tzwin(%s)" % repr(self._name) def __reduce__(self): return (self.__class__, (self._name,)) class tzwinlocal(tzwinbase): def __init__(self): with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey: keydict = valuestodict(tzlocalkey) self._std_abbr = keydict["StandardName"] self._dst_abbr = keydict["DaylightName"] try: tzkeyname = text_type('{kn}\\{sn}').format(kn=TZKEYNAME, sn=self._std_abbr) with winreg.OpenKey(handle, tzkeyname) as tzkey: _keydict = valuestodict(tzkey) self._display = _keydict["Display"] except OSError: self._display = None stdoffset = -keydict["Bias"]-keydict["StandardBias"] dstoffset = stdoffset-keydict["DaylightBias"] self._std_offset = datetime.timedelta(minutes=stdoffset) self._dst_offset = datetime.timedelta(minutes=dstoffset) # For reasons unclear, in this particular key, the day of week has been # moved to the END of the SYSTEMTIME structure. tup = struct.unpack("=8h", keydict["StandardStart"]) (self._stdmonth, self._stdweeknumber, # Last = 5 self._stdhour, self._stdminute) = tup[1:5] self._stddayofweek = tup[7] tup = struct.unpack("=8h", keydict["DaylightStart"]) (self._dstmonth, self._dstweeknumber, # Last = 5 self._dsthour, self._dstminute) = tup[1:5] self._dstdayofweek = tup[7] self._dst_base_offset_ = self._dst_offset - self._std_offset self.hasdst = self._get_hasdst() def __repr__(self): return "tzwinlocal()" def __str__(self): # str will return the standard name, not the daylight name. return "tzwinlocal(%s)" % repr(self._std_abbr) def __reduce__(self): return (self.__class__, ()) def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """ dayofweek == 0 means Sunday, whichweek 5 means last instance """ first = datetime.datetime(year, month, 1, hour, minute) # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6), # Because 7 % 7 = 0 weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1) wd = weekdayone + ((whichweek - 1) * ONEWEEK) if (wd.month != month): wd -= ONEWEEK return wd def valuestodict(key): """Convert a registry key's values to a dictionary.""" dout = {} size = winreg.QueryInfoKey(key)[1] tz_res = None for i in range(size): key_name, value, dtype = winreg.EnumValue(key, i) if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN: # If it's a DWORD (32-bit integer), it's stored as unsigned - convert # that to a proper signed integer if value & (1 << 31): value = value - (1 << 32) elif dtype == winreg.REG_SZ: # If it's a reference to the tzres DLL, load the actual string if value.startswith('@tzres'): tz_res = tz_res or tzres() value = tz_res.name_from_string(value) value = value.rstrip('\x00') # Remove trailing nulls dout[key_name] = value return dout
11,318
33.093373
88
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/tz/__init__.py
# -*- coding: utf-8 -*- from .tz import * from .tz import __doc__ #: Convenience constant providing a :class:`tzutc()` instance #: #: .. versionadded:: 2.7.0 UTC = tzutc() __all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", "tzstr", "tzical", "tzwin", "tzwinlocal", "gettz", "enfold", "datetime_ambiguous", "datetime_exists", "resolve_imaginary", "UTC", "DeprecatedTzFormatWarning"] class DeprecatedTzFormatWarning(Warning): """Warning raised when time zones are parsed from deprecated formats."""
551
29.666667
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/tz/_common.py
from six import PY3 from functools import wraps from datetime import datetime, timedelta, tzinfo ZERO = timedelta(0) __all__ = ['tzname_in_python2', 'enfold'] def tzname_in_python2(namefunc): """Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings """ def adjust_encoding(*args, **kwargs): name = namefunc(*args, **kwargs) if name is not None and not PY3: name = name.encode() return name return adjust_encoding # The following is adapted from Alexander Belopolsky's tz library # https://github.com/abalkin/tz if hasattr(datetime, 'fold'): # This is the pre-python 3.6 fold situation def enfold(dt, fold=1): """ Provides a unified interface for assigning the ``fold`` attribute to datetimes both before and after the implementation of PEP-495. :param fold: The value for the ``fold`` attribute in the returned datetime. This should be either 0 or 1. :return: Returns an object for which ``getattr(dt, 'fold', 0)`` returns ``fold`` for all versions of Python. In versions prior to Python 3.6, this is a ``_DatetimeWithFold`` object, which is a subclass of :py:class:`datetime.datetime` with the ``fold`` attribute added, if ``fold`` is 1. .. versionadded:: 2.6.0 """ return dt.replace(fold=fold) else: class _DatetimeWithFold(datetime): """ This is a class designed to provide a PEP 495-compliant interface for Python versions before 3.6. It is used only for dates in a fold, so the ``fold`` attribute is fixed at ``1``. .. versionadded:: 2.6.0 """ __slots__ = () def replace(self, *args, **kwargs): """ Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive datetime from an aware datetime with no conversion of date and time data. This is reimplemented in ``_DatetimeWithFold`` because pypy3 will return a ``datetime.datetime`` even if ``fold`` is unchanged. """ argnames = ( 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', 'tzinfo' ) for arg, argname in zip(args, argnames): if argname in kwargs: raise TypeError('Duplicate argument: {}'.format(argname)) kwargs[argname] = arg for argname in argnames: if argname not in kwargs: kwargs[argname] = getattr(self, argname) dt_class = self.__class__ if kwargs.get('fold', 1) else datetime return dt_class(**kwargs) @property def fold(self): return 1 def enfold(dt, fold=1): """ Provides a unified interface for assigning the ``fold`` attribute to datetimes both before and after the implementation of PEP-495. :param fold: The value for the ``fold`` attribute in the returned datetime. This should be either 0 or 1. :return: Returns an object for which ``getattr(dt, 'fold', 0)`` returns ``fold`` for all versions of Python. In versions prior to Python 3.6, this is a ``_DatetimeWithFold`` object, which is a subclass of :py:class:`datetime.datetime` with the ``fold`` attribute added, if ``fold`` is 1. .. versionadded:: 2.6.0 """ if getattr(dt, 'fold', 0) == fold: return dt args = dt.timetuple()[:6] args += (dt.microsecond, dt.tzinfo) if fold: return _DatetimeWithFold(*args) else: return datetime(*args) def _validate_fromutc_inputs(f): """ The CPython version of ``fromutc`` checks that the input is a ``datetime`` object and that ``self`` is attached as its ``tzinfo``. """ @wraps(f) def fromutc(self, dt): if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") return f(self, dt) return fromutc class _tzinfo(tzinfo): """ Base class for all ``dateutil`` ``tzinfo`` objects. """ def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ dt = dt.replace(tzinfo=self) wall_0 = enfold(dt, fold=0) wall_1 = enfold(dt, fold=1) same_offset = wall_0.utcoffset() == wall_1.utcoffset() same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None) return same_dt and not same_offset def _fold_status(self, dt_utc, dt_wall): """ Determine the fold status of a "wall" datetime, given a representation of the same datetime as a (naive) UTC datetime. This is calculated based on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all datetimes, and that this offset is the actual number of hours separating ``dt_utc`` and ``dt_wall``. :param dt_utc: Representation of the datetime as UTC :param dt_wall: Representation of the datetime as "wall time". This parameter must either have a `fold` attribute or have a fold-naive :class:`datetime.tzinfo` attached, otherwise the calculation may fail. """ if self.is_ambiguous(dt_wall): delta_wall = dt_wall - dt_utc _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst())) else: _fold = 0 return _fold def _fold(self, dt): return getattr(dt, 'fold', 0) def _fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurence, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object. """ # Re-implement the algorithm from Python's datetime.py dtoff = dt.utcoffset() if dtoff is None: raise ValueError("fromutc() requires a non-None utcoffset() " "result") # The original datetime.py code assumes that `dst()` defaults to # zero during ambiguous times. PEP 495 inverts this presumption, so # for pre-PEP 495 versions of python, we need to tweak the algorithm. dtdst = dt.dst() if dtdst is None: raise ValueError("fromutc() requires a non-None dst() result") delta = dtoff - dtdst dt += delta # Set fold=1 so we can default to being in the fold for # ambiguous dates. dtdst = enfold(dt, fold=1).dst() if dtdst is None: raise ValueError("fromutc(): dt.dst gave inconsistent " "results; cannot convert") return dt + dtdst @_validate_fromutc_inputs def fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurance, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object. """ dt_wall = self._fromutc(dt) # Calculate the fold status given the two datetimes. _fold = self._fold_status(dt, dt_wall) # Set the default fold value for ambiguous dates return enfold(dt_wall, fold=_fold) class tzrangebase(_tzinfo): """ This is an abstract base class for time zones represented by an annual transition into and out of DST. Child classes should implement the following methods: * ``__init__(self, *args, **kwargs)`` * ``transitions(self, year)`` - this is expected to return a tuple of datetimes representing the DST on and off transitions in standard time. A fully initialized ``tzrangebase`` subclass should also provide the following attributes: * ``hasdst``: Boolean whether or not the zone uses DST. * ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects representing the respective UTC offsets. * ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short abbreviations in DST and STD, respectively. * ``_hasdst``: Whether or not the zone has DST. .. versionadded:: 2.6.0 """ def __init__(self): raise NotImplementedError('tzrangebase is an abstract base class') def utcoffset(self, dt): isdst = self._isdst(dt) if isdst is None: return None elif isdst: return self._dst_offset else: return self._std_offset def dst(self, dt): isdst = self._isdst(dt) if isdst is None: return None elif isdst: return self._dst_base_offset else: return ZERO @tzname_in_python2 def tzname(self, dt): if self._isdst(dt): return self._dst_abbr else: return self._std_abbr def fromutc(self, dt): """ Given a datetime in UTC, return local time """ if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") # Get transitions - if there are none, fixed offset transitions = self.transitions(dt.year) if transitions is None: return dt + self.utcoffset(dt) # Get the transition times in UTC dston, dstoff = transitions dston -= self._std_offset dstoff -= self._std_offset utc_transitions = (dston, dstoff) dt_utc = dt.replace(tzinfo=None) isdst = self._naive_isdst(dt_utc, utc_transitions) if isdst: dt_wall = dt + self._dst_offset else: dt_wall = dt + self._std_offset _fold = int(not isdst and self.is_ambiguous(dt_wall)) return enfold(dt_wall, fold=_fold) def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ if not self.hasdst: return False start, end = self.transitions(dt.year) dt = dt.replace(tzinfo=None) return (end <= dt < end + self._dst_base_offset) def _isdst(self, dt): if not self.hasdst: return False elif dt is None: return None transitions = self.transitions(dt.year) if transitions is None: return False dt = dt.replace(tzinfo=None) isdst = self._naive_isdst(dt, transitions) # Handle ambiguous dates if not isdst and self.is_ambiguous(dt): return not self._fold(dt) else: return isdst def _naive_isdst(self, dt, transitions): dston, dstoff = transitions dt = dt.replace(tzinfo=None) if dston < dstoff: isdst = dston <= dt < dstoff else: isdst = not dstoff <= dt < dston return isdst @property def _dst_base_offset(self): return self._dst_offset - self._std_offset __hash__ = None def __ne__(self, other): return not (self == other) def __repr__(self): return "%s(...)" % self.__class__.__name__ __reduce__ = object.__reduce__
12,892
29.992788
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/dateutil/tz/tz.py
# -*- coding: utf-8 -*- """ This module offers timezone implementations subclassing the abstract :py:class:`datetime.tzinfo` type. There are classes to handle tzfile format files (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`, etc), TZ environment string (in all known formats), given ranges (with help from relative deltas), local machine timezone, fixed offset timezone, and UTC timezone. """ import datetime import struct import time import sys import os import bisect import six from six import string_types from six.moves import _thread from ._common import tzname_in_python2, _tzinfo from ._common import tzrangebase, enfold from ._common import _validate_fromutc_inputs from ._factories import _TzSingleton, _TzOffsetFactory from ._factories import _TzStrFactory try: from .win import tzwin, tzwinlocal except ImportError: tzwin = tzwinlocal = None ZERO = datetime.timedelta(0) EPOCH = datetime.datetime.utcfromtimestamp(0) EPOCHORDINAL = EPOCH.toordinal() @six.add_metaclass(_TzSingleton) class tzutc(datetime.tzinfo): """ This is a tzinfo object that represents the UTC time zone. **Examples:** .. doctest:: >>> from datetime import * >>> from dateutil.tz import * >>> datetime.now() datetime.datetime(2003, 9, 27, 9, 40, 1, 521290) >>> datetime.now(tzutc()) datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc()) >>> datetime.now(tzutc()).tzname() 'UTC' .. versionchanged:: 2.7.0 ``tzutc()`` is now a singleton, so the result of ``tzutc()`` will always return the same object. .. doctest:: >>> from dateutil.tz import tzutc, UTC >>> tzutc() is tzutc() True >>> tzutc() is UTC True """ def utcoffset(self, dt): return ZERO def dst(self, dt): return ZERO @tzname_in_python2 def tzname(self, dt): return "UTC" def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ return False @_validate_fromutc_inputs def fromutc(self, dt): """ Fast track version of fromutc() returns the original ``dt`` object for any valid :py:class:`datetime.datetime` object. """ return dt def __eq__(self, other): if not isinstance(other, (tzutc, tzoffset)): return NotImplemented return (isinstance(other, tzutc) or (isinstance(other, tzoffset) and other._offset == ZERO)) __hash__ = None def __ne__(self, other): return not (self == other) def __repr__(self): return "%s()" % self.__class__.__name__ __reduce__ = object.__reduce__ @six.add_metaclass(_TzOffsetFactory) class tzoffset(datetime.tzinfo): """ A simple class for representing a fixed offset from UTC. :param name: The timezone name, to be returned when ``tzname()`` is called. :param offset: The time zone offset in seconds, or (since version 2.6.0, represented as a :py:class:`datetime.timedelta` object). """ def __init__(self, name, offset): self._name = name try: # Allow a timedelta offset = offset.total_seconds() except (TypeError, AttributeError): pass self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self._offset def dst(self, dt): return ZERO @tzname_in_python2 def tzname(self, dt): return self._name @_validate_fromutc_inputs def fromutc(self, dt): return dt + self._offset def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ return False def __eq__(self, other): if not isinstance(other, tzoffset): return NotImplemented return self._offset == other._offset __hash__ = None def __ne__(self, other): return not (self == other) def __repr__(self): return "%s(%s, %s)" % (self.__class__.__name__, repr(self._name), int(self._offset.total_seconds())) __reduce__ = object.__reduce__ class tzlocal(_tzinfo): """ A :class:`tzinfo` subclass built around the ``time`` timezone functions. """ def __init__(self): super(tzlocal, self).__init__() self._std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: self._dst_offset = datetime.timedelta(seconds=-time.altzone) else: self._dst_offset = self._std_offset self._dst_saved = self._dst_offset - self._std_offset self._hasdst = bool(self._dst_saved) self._tznames = tuple(time.tzname) def utcoffset(self, dt): if dt is None and self._hasdst: return None if self._isdst(dt): return self._dst_offset else: return self._std_offset def dst(self, dt): if dt is None and self._hasdst: return None if self._isdst(dt): return self._dst_offset - self._std_offset else: return ZERO @tzname_in_python2 def tzname(self, dt): return self._tznames[self._isdst(dt)] def is_ambiguous(self, dt): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ naive_dst = self._naive_is_dst(dt) return (not naive_dst and (naive_dst != self._naive_is_dst(dt - self._dst_saved))) def _naive_is_dst(self, dt): timestamp = _datetime_to_timestamp(dt) return time.localtime(timestamp + time.timezone).tm_isdst def _isdst(self, dt, fold_naive=True): # We can't use mktime here. It is unstable when deciding if # the hour near to a change is DST or not. # # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst # # The code above yields the following result: # # >>> import tz, datetime # >>> t = tz.tzlocal() # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() # 'BRDT' # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() # 'BRST' # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() # 'BRST' # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() # 'BRDT' # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() # 'BRDT' # # Here is a more stable implementation: # if not self._hasdst: return False # Check for ambiguous times: dstval = self._naive_is_dst(dt) fold = getattr(dt, 'fold', None) if self.is_ambiguous(dt): if fold is not None: return not self._fold(dt) else: return True return dstval def __eq__(self, other): if isinstance(other, tzlocal): return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset) elif isinstance(other, tzutc): return (not self._hasdst and self._tznames[0] in {'UTC', 'GMT'} and self._std_offset == ZERO) elif isinstance(other, tzoffset): return (not self._hasdst and self._tznames[0] == other._name and self._std_offset == other._offset) else: return NotImplemented __hash__ = None def __ne__(self, other): return not (self == other) def __repr__(self): return "%s()" % self.__class__.__name__ __reduce__ = object.__reduce__ class _ttinfo(object): __slots__ = ["offset", "delta", "isdst", "abbr", "isstd", "isgmt", "dstoffset"] def __init__(self): for attr in self.__slots__: setattr(self, attr, None) def __repr__(self): l = [] for attr in self.__slots__: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) def __eq__(self, other): if not isinstance(other, _ttinfo): return NotImplemented return (self.offset == other.offset and self.delta == other.delta and self.isdst == other.isdst and self.abbr == other.abbr and self.isstd == other.isstd and self.isgmt == other.isgmt and self.dstoffset == other.dstoffset) __hash__ = None def __ne__(self, other): return not (self == other) def __getstate__(self): state = {} for name in self.__slots__: state[name] = getattr(self, name, None) return state def __setstate__(self, state): for name in self.__slots__: if name in state: setattr(self, name, state[name]) class _tzfile(object): """ Lightweight class for holding the relevant transition and time zone information read from binary tzfiles. """ attrs = ['trans_list', 'trans_list_utc', 'trans_idx', 'ttinfo_list', 'ttinfo_std', 'ttinfo_dst', 'ttinfo_before', 'ttinfo_first'] def __init__(self, **kwargs): for attr in self.attrs: setattr(self, attr, kwargs.get(attr, None)) class tzfile(_tzinfo): """ This is a ``tzinfo`` subclass thant allows one to use the ``tzfile(5)`` format timezone files to extract current and historical zone information. :param fileobj: This can be an opened file stream or a file name that the time zone information can be read from. :param filename: This is an optional parameter specifying the source of the time zone information in the event that ``fileobj`` is a file object. If omitted and ``fileobj`` is a file stream, this parameter will be set either to ``fileobj``'s ``name`` attribute or to ``repr(fileobj)``. See `Sources for Time Zone and Daylight Saving Time Data <https://data.iana.org/time-zones/tz-link.html>`_ for more information. Time zone files can be compiled from the `IANA Time Zone database files <https://www.iana.org/time-zones>`_ with the `zic time zone compiler <https://www.freebsd.org/cgi/man.cgi?query=zic&sektion=8>`_ .. note:: Only construct a ``tzfile`` directly if you have a specific timezone file on disk that you want to read into a Python ``tzinfo`` object. If you want to get a ``tzfile`` representing a specific IANA zone, (e.g. ``'America/New_York'``), you should call :func:`dateutil.tz.gettz` with the zone identifier. **Examples:** Using the US Eastern time zone as an example, we can see that a ``tzfile`` provides time zone information for the standard Daylight Saving offsets: .. testsetup:: tzfile from dateutil.tz import gettz from datetime import datetime .. doctest:: tzfile >>> NYC = gettz('America/New_York') >>> NYC tzfile('/usr/share/zoneinfo/America/New_York') >>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST 2016-01-03 00:00:00-05:00 >>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT 2016-07-07 00:00:00-04:00 The ``tzfile`` structure contains a fully history of the time zone, so historical dates will also have the right offsets. For example, before the adoption of the UTC standards, New York used local solar mean time: .. doctest:: tzfile >>> print(datetime(1901, 4, 12, tzinfo=NYC)) # LMT 1901-04-12 00:00:00-04:56 And during World War II, New York was on "Eastern War Time", which was a state of permanent daylight saving time: .. doctest:: tzfile >>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT 1944-02-07 00:00:00-04:00 """ def __init__(self, fileobj, filename=None): super(tzfile, self).__init__() file_opened_here = False if isinstance(fileobj, string_types): self._filename = fileobj fileobj = open(fileobj, 'rb') file_opened_here = True elif filename is not None: self._filename = filename elif hasattr(fileobj, "name"): self._filename = fileobj.name else: self._filename = repr(fileobj) if fileobj is not None: if not file_opened_here: fileobj = _ContextWrapper(fileobj) with fileobj as file_stream: tzobj = self._read_tzfile(file_stream) self._set_tzdata(tzobj) def _set_tzdata(self, tzobj): """ Set the time zone data of this object from a _tzfile object """ # Copy the relevant attributes over as private attributes for attr in _tzfile.attrs: setattr(self, '_' + attr, getattr(tzobj, attr)) def _read_tzfile(self, fileobj): out = _tzfile() # From tzfile(5): # # The time zone information files used by tzset(3) # begin with the magic characters "TZif" to identify # them as time zone information files, followed by # sixteen bytes reserved for future use, followed by # six four-byte values of type long, written in a # ``standard'' byte order (the high-order byte # of the value is written first). if fileobj.read(4).decode() != "TZif": raise ValueError("magic not found") fileobj.read(16) ( # The number of UTC/local indicators stored in the file. ttisgmtcnt, # The number of standard/wall indicators stored in the file. ttisstdcnt, # The number of leap seconds for which data is # stored in the file. leapcnt, # The number of "transition times" for which data # is stored in the file. timecnt, # The number of "local time types" for which data # is stored in the file (must not be zero). typecnt, # The number of characters of "time zone # abbreviation strings" stored in the file. charcnt, ) = struct.unpack(">6l", fileobj.read(24)) # The above header is followed by tzh_timecnt four-byte # values of type long, sorted in ascending order. # These values are written in ``standard'' byte order. # Each is used as a transition time (as returned by # time(2)) at which the rules for computing local time # change. if timecnt: out.trans_list_utc = list(struct.unpack(">%dl" % timecnt, fileobj.read(timecnt*4))) else: out.trans_list_utc = [] # Next come tzh_timecnt one-byte values of type unsigned # char; each one tells which of the different types of # ``local time'' types described in the file is associated # with the same-indexed transition time. These values # serve as indices into an array of ttinfo structures that # appears next in the file. if timecnt: out.trans_idx = struct.unpack(">%dB" % timecnt, fileobj.read(timecnt)) else: out.trans_idx = [] # Each ttinfo structure is written as a four-byte value # for tt_gmtoff of type long, in a standard byte # order, followed by a one-byte value for tt_isdst # and a one-byte value for tt_abbrind. In each # structure, tt_gmtoff gives the number of # seconds to be added to UTC, tt_isdst tells whether # tm_isdst should be set by localtime(3), and # tt_abbrind serves as an index into the array of # time zone abbreviation characters that follow the # ttinfo structure(s) in the file. ttinfo = [] for i in range(typecnt): ttinfo.append(struct.unpack(">lbb", fileobj.read(6))) abbr = fileobj.read(charcnt).decode() # Then there are tzh_leapcnt pairs of four-byte # values, written in standard byte order; the # first value of each pair gives the time (as # returned by time(2)) at which a leap second # occurs; the second gives the total number of # leap seconds to be applied after the given time. # The pairs of values are sorted in ascending order # by time. # Not used, for now (but seek for correct file position) if leapcnt: fileobj.seek(leapcnt * 8, os.SEEK_CUR) # Then there are tzh_ttisstdcnt standard/wall # indicators, each stored as a one-byte value; # they tell whether the transition times associated # with local time types were specified as standard # time or wall clock time, and are used when # a time zone file is used in handling POSIX-style # time zone environment variables. if ttisstdcnt: isstd = struct.unpack(">%db" % ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally, there are tzh_ttisgmtcnt UTC/local # indicators, each stored as a one-byte value; # they tell whether the transition times associated # with local time types were specified as UTC or # local time, and are used when a time zone file # is used in handling POSIX-style time zone envi- # ronment variables. if ttisgmtcnt: isgmt = struct.unpack(">%db" % ttisgmtcnt, fileobj.read(ttisgmtcnt)) # Build ttinfo list out.ttinfo_list = [] for i in range(typecnt): gmtoff, isdst, abbrind = ttinfo[i] # Round to full-minutes if that's not the case. Python's # datetime doesn't accept sub-minute timezones. Check # http://python.org/sf/1447945 for some information. gmtoff = 60 * ((gmtoff + 30) // 60) tti = _ttinfo() tti.offset = gmtoff tti.dstoffset = datetime.timedelta(0) tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst = isdst tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)] tti.isstd = (ttisstdcnt > i and isstd[i] != 0) tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0) out.ttinfo_list.append(tti) # Replace ttinfo indexes for ttinfo objects. out.trans_idx = [out.ttinfo_list[idx] for idx in out.trans_idx] # Set standard, dst, and before ttinfos. before will be # used when a given time is before any transitions, # and will be set to the first non-dst ttinfo, or to # the first dst, if all of them are dst. out.ttinfo_std = None out.ttinfo_dst = None out.ttinfo_before = None if out.ttinfo_list: if not out.trans_list_utc: out.ttinfo_std = out.ttinfo_first = out.ttinfo_list[0] else: for i in range(timecnt-1, -1, -1): tti = out.trans_idx[i] if not out.ttinfo_std and not tti.isdst: out.ttinfo_std = tti elif not out.ttinfo_dst and tti.isdst: out.ttinfo_dst = tti if out.ttinfo_std and out.ttinfo_dst: break else: if out.ttinfo_dst and not out.ttinfo_std: out.ttinfo_std = out.ttinfo_dst for tti in out.ttinfo_list: if not tti.isdst: out.ttinfo_before = tti break else: out.ttinfo_before = out.ttinfo_list[0] # Now fix transition times to become relative to wall time. # # I'm not sure about this. In my tests, the tz source file # is setup to wall time, and in the binary file isstd and # isgmt are off, so it should be in wall time. OTOH, it's # always in gmt time. Let me know if you have comments # about this. laststdoffset = None out.trans_list = [] for i, tti in enumerate(out.trans_idx): if not tti.isdst: offset = tti.offset laststdoffset = offset else: if laststdoffset is not None: # Store the DST offset as well and update it in the list tti.dstoffset = tti.offset - laststdoffset out.trans_idx[i] = tti offset = laststdoffset or 0 out.trans_list.append(out.trans_list_utc[i] + offset) # In case we missed any DST offsets on the way in for some reason, make # a second pass over the list, looking for the /next/ DST offset. laststdoffset = None for i in reversed(range(len(out.trans_idx))): tti = out.trans_idx[i] if tti.isdst: if not (tti.dstoffset or laststdoffset is None): tti.dstoffset = tti.offset - laststdoffset else: laststdoffset = tti.offset if not isinstance(tti.dstoffset, datetime.timedelta): tti.dstoffset = datetime.timedelta(seconds=tti.dstoffset) out.trans_idx[i] = tti out.trans_idx = tuple(out.trans_idx) out.trans_list = tuple(out.trans_list) out.trans_list_utc = tuple(out.trans_list_utc) return out def _find_last_transition(self, dt, in_utc=False): # If there's no list, there are no transitions to find if not self._trans_list: return None timestamp = _datetime_to_timestamp(dt) # Find where the timestamp fits in the transition list - if the # timestamp is a transition time, it's part of the "after" period. trans_list = self._trans_list_utc if in_utc else self._trans_list idx = bisect.bisect_right(trans_list, timestamp) # We want to know when the previous transition was, so subtract off 1 return idx - 1 def _get_ttinfo(self, idx): # For no list or after the last transition, default to _ttinfo_std if idx is None or (idx + 1) >= len(self._trans_list): return self._ttinfo_std # If there is a list and the time is before it, return _ttinfo_before if idx < 0: return self._ttinfo_before return self._trans_idx[idx] def _find_ttinfo(self, dt): idx = self._resolve_ambiguous_time(dt) return self._get_ttinfo(idx) def fromutc(self, dt): """ The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. :param dt: A :py:class:`datetime.datetime` object. :raises TypeError: Raised if ``dt`` is not a :py:class:`datetime.datetime` object. :raises ValueError: Raised if this is called with a ``dt`` which does not have this ``tzinfo`` attached. :return: Returns a :py:class:`datetime.datetime` object representing the wall time in ``self``'s time zone. """ # These isinstance checks are in datetime.tzinfo, so we'll preserve # them, even if we don't care about duck typing. if not isinstance(dt, datetime.datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") # First treat UTC as wall time and get the transition we're in. idx = self._find_last_transition(dt, in_utc=True) tti = self._get_ttinfo(idx) dt_out = dt + datetime.timedelta(seconds=tti.offset) fold = self.is_ambiguous(dt_out, idx=idx) return enfold(dt_out, fold=int(fold)) def is_ambiguous(self, dt, idx=None): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ if idx is None: idx = self._find_last_transition(dt) # Calculate the difference in offsets from current to previous timestamp = _datetime_to_timestamp(dt) tti = self._get_ttinfo(idx) if idx is None or idx <= 0: return False od = self._get_ttinfo(idx - 1).offset - tti.offset tt = self._trans_list[idx] # Transition time return timestamp < tt + od def _resolve_ambiguous_time(self, dt): idx = self._find_last_transition(dt) # If we have no transitions, return the index _fold = self._fold(dt) if idx is None or idx == 0: return idx # If it's ambiguous and we're in a fold, shift to a different index. idx_offset = int(not _fold and self.is_ambiguous(dt, idx)) return idx - idx_offset def utcoffset(self, dt): if dt is None: return None if not self._ttinfo_std: return ZERO return self._find_ttinfo(dt).delta def dst(self, dt): if dt is None: return None if not self._ttinfo_dst: return ZERO tti = self._find_ttinfo(dt) if not tti.isdst: return ZERO # The documentation says that utcoffset()-dst() must # be constant for every dt. return tti.dstoffset @tzname_in_python2 def tzname(self, dt): if not self._ttinfo_std or dt is None: return None return self._find_ttinfo(dt).abbr def __eq__(self, other): if not isinstance(other, tzfile): return NotImplemented return (self._trans_list == other._trans_list and self._trans_idx == other._trans_idx and self._ttinfo_list == other._ttinfo_list) __hash__ = None def __ne__(self, other): return not (self == other) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self._filename)) def __reduce__(self): return self.__reduce_ex__(None) def __reduce_ex__(self, protocol): return (self.__class__, (None, self._filename), self.__dict__) class tzrange(tzrangebase): """ The ``tzrange`` object is a time zone specified by a set of offsets and abbreviations, equivalent to the way the ``TZ`` variable can be specified in POSIX-like systems, but using Python delta objects to specify DST start, end and offsets. :param stdabbr: The abbreviation for standard time (e.g. ``'EST'``). :param stdoffset: An integer or :class:`datetime.timedelta` object or equivalent specifying the base offset from UTC. If unspecified, +00:00 is used. :param dstabbr: The abbreviation for DST / "Summer" time (e.g. ``'EDT'``). If specified, with no other DST information, DST is assumed to occur and the default behavior or ``dstoffset``, ``start`` and ``end`` is used. If unspecified and no other DST information is specified, it is assumed that this zone has no DST. If this is unspecified and other DST information is *is* specified, DST occurs in the zone but the time zone abbreviation is left unchanged. :param dstoffset: A an integer or :class:`datetime.timedelta` object or equivalent specifying the UTC offset during DST. If unspecified and any other DST information is specified, it is assumed to be the STD offset +1 hour. :param start: A :class:`relativedelta.relativedelta` object or equivalent specifying the time and time of year that daylight savings time starts. To specify, for example, that DST starts at 2AM on the 2nd Sunday in March, pass: ``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))`` If unspecified and any other DST information is specified, the default value is 2 AM on the first Sunday in April. :param end: A :class:`relativedelta.relativedelta` object or equivalent representing the time and time of year that daylight savings time ends, with the same specification method as in ``start``. One note is that this should point to the first time in the *standard* zone, so if a transition occurs at 2AM in the DST zone and the clocks are set back 1 hour to 1AM, set the ``hours`` parameter to +1. **Examples:** .. testsetup:: tzrange from dateutil.tz import tzrange, tzstr .. doctest:: tzrange >>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT") True >>> from dateutil.relativedelta import * >>> range1 = tzrange("EST", -18000, "EDT") >>> range2 = tzrange("EST", -18000, "EDT", -14400, ... relativedelta(hours=+2, month=4, day=1, ... weekday=SU(+1)), ... relativedelta(hours=+1, month=10, day=31, ... weekday=SU(-1))) >>> tzstr('EST5EDT') == range1 == range2 True """ def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None): global relativedelta from dateutil import relativedelta self._std_abbr = stdabbr self._dst_abbr = dstabbr try: stdoffset = stdoffset.total_seconds() except (TypeError, AttributeError): pass try: dstoffset = dstoffset.total_seconds() except (TypeError, AttributeError): pass if stdoffset is not None: self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO if dstoffset is not None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset is not None: self._dst_offset = self._std_offset + datetime.timedelta(hours=+1) else: self._dst_offset = ZERO if dstabbr and start is None: self._start_delta = relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta = start if dstabbr and end is None: self._end_delta = relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta = end self._dst_base_offset_ = self._dst_offset - self._std_offset self.hasdst = bool(self._start_delta) def transitions(self, year): """ For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. :return: Returns a :class:`tuple` of :class:`datetime.datetime` objects, ``(dston, dstoff)`` for zones with an annual DST transition, or ``None`` for fixed offset zones. """ if not self.hasdst: return None base_year = datetime.datetime(year, 1, 1) start = base_year + self._start_delta end = base_year + self._end_delta return (start, end) def __eq__(self, other): if not isinstance(other, tzrange): return NotImplemented return (self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr and self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and self._start_delta == other._start_delta and self._end_delta == other._end_delta) @property def _dst_base_offset(self): return self._dst_base_offset_ @six.add_metaclass(_TzStrFactory) class tzstr(tzrange): """ ``tzstr`` objects are time zone objects specified by a time-zone string as it would be passed to a ``TZ`` variable on POSIX-style systems (see the `GNU C Library: TZ Variable`_ for more details). There is one notable exception, which is that POSIX-style time zones use an inverted offset format, so normally ``GMT+3`` would be parsed as an offset 3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX behavior, pass a ``True`` value to ``posix_offset``. The :class:`tzrange` object provides the same functionality, but is specified using :class:`relativedelta.relativedelta` objects. rather than strings. :param s: A time zone string in ``TZ`` variable format. This can be a :class:`bytes` (2.x: :class:`str`), :class:`str` (2.x: :class:`unicode`) or a stream emitting unicode characters (e.g. :class:`StringIO`). :param posix_offset: Optional. If set to ``True``, interpret strings such as ``GMT+3`` or ``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the POSIX standard. .. caution:: Prior to version 2.7.0, this function also supported time zones in the format: * ``EST5EDT,4,0,6,7200,10,0,26,7200,3600`` * ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600`` This format is non-standard and has been deprecated; this function will raise a :class:`DeprecatedTZFormatWarning` until support is removed in a future version. .. _`GNU C Library: TZ Variable`: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html """ def __init__(self, s, posix_offset=False): global parser from dateutil.parser import _parser as parser self._s = s res = parser._parsetz(s) if res is None or res.any_unused_tokens: raise ValueError("unknown string format") # Here we break the compatibility with the TZ variable handling. # GMT-3 actually *means* the timezone -3. if res.stdabbr in ("GMT", "UTC") and not posix_offset: res.stdoffset *= -1 # We must initialize it first, since _delta() needs # _std_offset and _dst_offset set. Use False in start/end # to avoid building it two times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False) if not res.dstabbr: self._start_delta = None self._end_delta = None else: self._start_delta = self._delta(res.start) if self._start_delta: self._end_delta = self._delta(res.end, isend=1) self.hasdst = bool(self._start_delta) def _delta(self, x, isend=0): from dateutil import relativedelta kwargs = {} if x.month is not None: kwargs["month"] = x.month if x.weekday is not None: kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) if x.week > 0: kwargs["day"] = 1 else: kwargs["day"] = 31 elif x.day: kwargs["day"] = x.day elif x.yday is not None: kwargs["yearday"] = x.yday elif x.jyday is not None: kwargs["nlyearday"] = x.jyday if not kwargs: # Default is to start on first sunday of april, and end # on last sunday of october. if not isend: kwargs["month"] = 4 kwargs["day"] = 1 kwargs["weekday"] = relativedelta.SU(+1) else: kwargs["month"] = 10 kwargs["day"] = 31 kwargs["weekday"] = relativedelta.SU(-1) if x.time is not None: kwargs["seconds"] = x.time else: # Default is 2AM. kwargs["seconds"] = 7200 if isend: # Convert to standard time, to follow the documented way # of working with the extra hour. See the documentation # of the tzinfo class. delta = self._dst_offset - self._std_offset kwargs["seconds"] -= delta.seconds + delta.days * 86400 return relativedelta.relativedelta(**kwargs) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp(object): def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom self.isdst = isdst self.tzname = tzname self.rrule = rrule class _tzicalvtz(_tzinfo): def __init__(self, tzid, comps=[]): super(_tzicalvtz, self).__init__() self._tzid = tzid self._comps = comps self._cachedate = [] self._cachecomp = [] self._cache_lock = _thread.allocate_lock() def _find_comp(self, dt): if len(self._comps) == 1: return self._comps[0] dt = dt.replace(tzinfo=None) try: with self._cache_lock: return self._cachecomp[self._cachedate.index( (dt, self._fold(dt)))] except ValueError: pass lastcompdt = None lastcomp = None for comp in self._comps: compdt = self._find_compdt(comp, dt) if compdt and (not lastcompdt or lastcompdt < compdt): lastcompdt = compdt lastcomp = comp if not lastcomp: # RFC says nothing about what to do when a given # time is before the first onset date. We'll look for the # first standard component, or the first component, if # none is found. for comp in self._comps: if not comp.isdst: lastcomp = comp break else: lastcomp = comp[0] with self._cache_lock: self._cachedate.insert(0, (dt, self._fold(dt))) self._cachecomp.insert(0, lastcomp) if len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop() return lastcomp def _find_compdt(self, comp, dt): if comp.tzoffsetdiff < ZERO and self._fold(dt): dt -= comp.tzoffsetdiff compdt = comp.rrule.before(dt, inc=True) return compdt def utcoffset(self, dt): if dt is None: return None return self._find_comp(dt).tzoffsetto def dst(self, dt): comp = self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff else: return ZERO @tzname_in_python2 def tzname(self, dt): return self._find_comp(dt).tzname def __repr__(self): return "<tzicalvtz %s>" % repr(self._tzid) __reduce__ = object.__reduce__ class tzical(object): """ This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects. :param `fileobj`: A file or stream in iCalendar format, which should be UTF-8 encoded with CRLF endings. .. _`RFC 5545`: https://tools.ietf.org/html/rfc5545 """ def __init__(self, fileobj): global rrule from dateutil import rrule if isinstance(fileobj, string_types): self._s = fileobj # ical should be encoded in UTF-8 with CRLF fileobj = open(fileobj, 'r') else: self._s = getattr(fileobj, 'name', repr(fileobj)) fileobj = _ContextWrapper(fileobj) self._vtz = {} with fileobj as fobj: self._parse_rfc(fobj.read()) def keys(self): """ Retrieves the available time zones as a list. """ return list(self._vtz.keys()) def get(self, tzid=None): """ Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. :param tzid: If there is exactly one time zone available, omitting ``tzid`` or passing :py:const:`None` value returns it. Otherwise a valid key (which can be retrieved from :func:`keys`) is required. :raises ValueError: Raised if ``tzid`` is not specified but there are either more or fewer than 1 zone defined. :returns: Returns either a :py:class:`datetime.tzinfo` object representing the relevant time zone or :py:const:`None` if the ``tzid`` was not found. """ if tzid is None: if len(self._vtz) == 0: raise ValueError("no timezones defined") elif len(self._vtz) > 1: raise ValueError("more than one timezone available") tzid = next(iter(self._vtz)) return self._vtz.get(tzid) def _parse_offset(self, s): s = s.strip() if not s: raise ValueError("empty offset") if s[0] in ('+', '-'): signal = (-1, +1)[s[0] == '+'] s = s[1:] else: signal = +1 if len(s) == 4: return (int(s[:2]) * 3600 + int(s[2:]) * 60) * signal elif len(s) == 6: return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal else: raise ValueError("invalid offset: " + s) def _parse_rfc(self, s): lines = s.splitlines() if not lines: raise ValueError("empty string") # Unfold i = 0 while i < len(lines): line = lines[i].rstrip() if not line: del lines[i] elif i > 0 and line[0] == " ": lines[i-1] += line[1:] del lines[i] else: i += 1 tzid = None comps = [] invtz = False comptype = None for line in lines: if not line: continue name, value = line.split(':', 1) parms = name.split(';') if not parms: raise ValueError("empty property name") name = parms[0].upper() parms = parms[1:] if invtz: if name == "BEGIN": if value in ("STANDARD", "DAYLIGHT"): # Process component pass else: raise ValueError("unknown component: "+value) comptype = value founddtstart = False tzoffsetfrom = None tzoffsetto = None rrulelines = [] tzname = None elif name == "END": if value == "VTIMEZONE": if comptype: raise ValueError("component not closed: "+comptype) if not tzid: raise ValueError("mandatory TZID not found") if not comps: raise ValueError( "at least one component is needed") # Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz = False elif value == comptype: if not founddtstart: raise ValueError("mandatory DTSTART not found") if tzoffsetfrom is None: raise ValueError( "mandatory TZOFFSETFROM not found") if tzoffsetto is None: raise ValueError( "mandatory TZOFFSETFROM not found") # Process component rr = None if rrulelines: rr = rrule.rrulestr("\n".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == "DAYLIGHT"), tzname, rr) comps.append(comp) comptype = None else: raise ValueError("invalid component end: "+value) elif comptype: if name == "DTSTART": # DTSTART in VTIMEZONE takes a subset of valid RRULE # values under RFC 5545. for parm in parms: if parm != 'VALUE=DATE-TIME': msg = ('Unsupported DTSTART param in ' + 'VTIMEZONE: ' + parm) raise ValueError(msg) rrulelines.append(line) founddtstart = True elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"): rrulelines.append(line) elif name == "TZOFFSETFROM": if parms: raise ValueError( "unsupported %s parm: %s " % (name, parms[0])) tzoffsetfrom = self._parse_offset(value) elif name == "TZOFFSETTO": if parms: raise ValueError( "unsupported TZOFFSETTO parm: "+parms[0]) tzoffsetto = self._parse_offset(value) elif name == "TZNAME": if parms: raise ValueError( "unsupported TZNAME parm: "+parms[0]) tzname = value elif name == "COMMENT": pass else: raise ValueError("unsupported property: "+name) else: if name == "TZID": if parms: raise ValueError( "unsupported TZID parm: "+parms[0]) tzid = value elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): pass else: raise ValueError("unsupported property: "+name) elif name == "BEGIN" and value == "VTIMEZONE": tzid = None comps = [] invtz = True def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self._s)) if sys.platform != "win32": TZFILES = ["/etc/localtime", "localtime"] TZPATHS = ["/usr/share/zoneinfo", "/usr/lib/zoneinfo", "/usr/share/lib/zoneinfo", "/etc/zoneinfo"] else: TZFILES = [] TZPATHS = [] def __get_gettz(): tzlocal_classes = (tzlocal,) if tzwinlocal is not None: tzlocal_classes += (tzwinlocal,) class GettzFunc(object): """ Retrieve a time zone object from a string representation This function is intended to retrieve the :py:class:`tzinfo` subclass that best represents the time zone that would be used if a POSIX `TZ variable`_ were set to the same value. If no argument or an empty string is passed to ``gettz``, local time is returned: .. code-block:: python3 >>> gettz() tzfile('/etc/localtime') This function is also the preferred way to map IANA tz database keys to :class:`tzfile` objects: .. code-block:: python3 >>> gettz('Pacific/Kiritimati') tzfile('/usr/share/zoneinfo/Pacific/Kiritimati') On Windows, the standard is extended to include the Windows-specific zone names provided by the operating system: .. code-block:: python3 >>> gettz('Egypt Standard Time') tzwin('Egypt Standard Time') Passing a GNU ``TZ`` style string time zone specification returns a :class:`tzstr` object: .. code-block:: python3 >>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') :param name: A time zone name (IANA, or, on Windows, Windows keys), location of a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone specifier. An empty string, no argument or ``None`` is interpreted as local time. :return: Returns an instance of one of ``dateutil``'s :py:class:`tzinfo` subclasses. .. versionchanged:: 2.7.0 After version 2.7.0, any two calls to ``gettz`` using the same input strings will return the same object: .. code-block:: python3 >>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago') True In addition to improving performance, this ensures that `"same zone" semantics`_ are used for datetimes in the same zone. .. _`TZ variable`: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html .. _`"same zone" semantics`: https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html """ def __init__(self): self.__instances = {} self._cache_lock = _thread.allocate_lock() def __call__(self, name=None): with self._cache_lock: rv = self.__instances.get(name, None) if rv is None: rv = self.nocache(name=name) if not (name is None or isinstance(rv, tzlocal_classes)): # tzlocal is slightly more complicated than the other # time zone providers because it depends on environment # at construction time, so don't cache that. self.__instances[name] = rv return rv def cache_clear(self): with self._cache_lock: self.__instances = {} @staticmethod def nocache(name=None): """A non-cached version of gettz""" tz = None if not name: try: name = os.environ["TZ"] except KeyError: pass if name is None or name == ":": for filepath in TZFILES: if not os.path.isabs(filepath): filename = filepath for path in TZPATHS: filepath = os.path.join(path, filename) if os.path.isfile(filepath): break else: continue if os.path.isfile(filepath): try: tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz = tzlocal() else: if name.startswith(":"): name = name[1:] if os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name) else: tz = None else: for path in TZPATHS: filepath = os.path.join(path, name) if not os.path.isfile(filepath): filepath = filepath.replace(' ', '_') if not os.path.isfile(filepath): continue try: tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz = None if tzwin is not None: try: tz = tzwin(name) except WindowsError: tz = None if not tz: from dateutil.zoneinfo import get_zonefile_instance tz = get_zonefile_instance().get(name) if not tz: for c in name: # name is not a tzstr unless it has at least # one offset. For short values of "name", an # explicit for loop seems to be the fastest way # To determine if a string contains a digit if c in "0123456789": try: tz = tzstr(name) except ValueError: pass break else: if name in ("GMT", "UTC"): tz = tzutc() elif name in time.tzname: tz = tzlocal() return tz return GettzFunc() gettz = __get_gettz() del __get_gettz def datetime_exists(dt, tz=None): """ Given a datetime and a time zone, determine whether or not a given datetime would fall in a gap. :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` is provided.) :param tz: A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If ``None`` or not provided, the datetime's own time zone will be used. :return: Returns a boolean value whether or not the "wall time" exists in ``tz``. .. versionadded:: 2.7.0 """ if tz is None: if dt.tzinfo is None: raise ValueError('Datetime is naive and no time zone provided.') tz = dt.tzinfo dt = dt.replace(tzinfo=None) # This is essentially a test of whether or not the datetime can survive # a round trip to UTC. dt_rt = dt.replace(tzinfo=tz).astimezone(tzutc()).astimezone(tz) dt_rt = dt_rt.replace(tzinfo=None) return dt == dt_rt def datetime_ambiguous(dt, tz=None): """ Given a datetime and a time zone, determine whether or not a given datetime is ambiguous (i.e if there are two times differentiated only by their DST status). :param dt: A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` is provided.) :param tz: A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If ``None`` or not provided, the datetime's own time zone will be used. :return: Returns a boolean value whether or not the "wall time" is ambiguous in ``tz``. .. versionadded:: 2.6.0 """ if tz is None: if dt.tzinfo is None: raise ValueError('Datetime is naive and no time zone provided.') tz = dt.tzinfo # If a time zone defines its own "is_ambiguous" function, we'll use that. is_ambiguous_fn = getattr(tz, 'is_ambiguous', None) if is_ambiguous_fn is not None: try: return tz.is_ambiguous(dt) except Exception: pass # If it doesn't come out and tell us it's ambiguous, we'll just check if # the fold attribute has any effect on this particular date and time. dt = dt.replace(tzinfo=tz) wall_0 = enfold(dt, fold=0) wall_1 = enfold(dt, fold=1) same_offset = wall_0.utcoffset() == wall_1.utcoffset() same_dst = wall_0.dst() == wall_1.dst() return not (same_offset and same_dst) def resolve_imaginary(dt): """ Given a datetime that may be imaginary, return an existing datetime. This function assumes that an imaginary datetime represents what the wall time would be in a zone had the offset transition not occurred, so it will always fall forward by the transition's change in offset. .. doctest:: >>> from dateutil import tz >>> from datetime import datetime >>> NYC = tz.gettz('America/New_York') >>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC))) 2017-03-12 03:30:00-04:00 >>> KIR = tz.gettz('Pacific/Kiritimati') >>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR))) 1995-01-02 12:30:00+14:00 As a note, :func:`datetime.astimezone` is guaranteed to produce a valid, existing datetime, so a round-trip to and from UTC is sufficient to get an extant datetime, however, this generally "falls back" to an earlier time rather than falling forward to the STD side (though no guarantees are made about this behavior). :param dt: A :class:`datetime.datetime` which may or may not exist. :return: Returns an existing :class:`datetime.datetime`. If ``dt`` was not imaginary, the datetime returned is guaranteed to be the same object passed to the function. .. versionadded:: 2.7.0 """ if dt.tzinfo is not None and not datetime_exists(dt): curr_offset = (dt + datetime.timedelta(hours=24)).utcoffset() old_offset = (dt - datetime.timedelta(hours=24)).utcoffset() dt += curr_offset - old_offset return dt def _datetime_to_timestamp(dt): """ Convert a :class:`datetime.datetime` object to an epoch timestamp in seconds since January 1, 1970, ignoring the time zone. """ return (dt.replace(tzinfo=None) - EPOCH).total_seconds() class _ContextWrapper(object): """ Class for wrapping contexts so that they are passed through in a with statement. """ def __init__(self, context): self.context = context def __enter__(self): return self.context def __exit__(*args, **kwargs): pass # vim:ts=4:sw=4:et
60,472
32.859462
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/fontconfig_pattern.py
""" A module for parsing and generating fontconfig patterns. See the `fontconfig pattern specification <https://www.freedesktop.org/software/fontconfig/fontconfig-user.html>`_ for more information. """ # This class is defined here because it must be available in: # - The old-style config framework (:file:`rcsetup.py`) # - The font manager (:file:`font_manager.py`) # It probably logically belongs in :file:`font_manager.py`, but placing it # there would have created cyclical dependency problems. from __future__ import (absolute_import, division, print_function, unicode_literals) import six import re from pyparsing import (Literal, ZeroOrMore, Optional, Regex, StringEnd, ParseException, Suppress) try: from functools import lru_cache except ImportError: from backports.functools_lru_cache import lru_cache family_punc = r'\\\-:,' family_unescape = re.compile(r'\\([%s])' % family_punc).sub family_escape = re.compile(r'([%s])' % family_punc).sub value_punc = r'\\=_:,' value_unescape = re.compile(r'\\([%s])' % value_punc).sub value_escape = re.compile(r'([%s])' % value_punc).sub class FontconfigPatternParser(object): """A simple pyparsing-based parser for fontconfig-style patterns. See the `fontconfig pattern specification <https://www.freedesktop.org/software/fontconfig/fontconfig-user.html>`_ for more information. """ _constants = { 'thin' : ('weight', 'light'), 'extralight' : ('weight', 'light'), 'ultralight' : ('weight', 'light'), 'light' : ('weight', 'light'), 'book' : ('weight', 'book'), 'regular' : ('weight', 'regular'), 'normal' : ('weight', 'normal'), 'medium' : ('weight', 'medium'), 'demibold' : ('weight', 'demibold'), 'semibold' : ('weight', 'semibold'), 'bold' : ('weight', 'bold'), 'extrabold' : ('weight', 'extra bold'), 'black' : ('weight', 'black'), 'heavy' : ('weight', 'heavy'), 'roman' : ('slant', 'normal'), 'italic' : ('slant', 'italic'), 'oblique' : ('slant', 'oblique'), 'ultracondensed' : ('width', 'ultra-condensed'), 'extracondensed' : ('width', 'extra-condensed'), 'condensed' : ('width', 'condensed'), 'semicondensed' : ('width', 'semi-condensed'), 'expanded' : ('width', 'expanded'), 'extraexpanded' : ('width', 'extra-expanded'), 'ultraexpanded' : ('width', 'ultra-expanded') } def __init__(self): family = Regex(r'([^%s]|(\\[%s]))*' % (family_punc, family_punc)) \ .setParseAction(self._family) size = Regex(r"([0-9]+\.?[0-9]*|\.[0-9]+)") \ .setParseAction(self._size) name = Regex(r'[a-z]+') \ .setParseAction(self._name) value = Regex(r'([^%s]|(\\[%s]))*' % (value_punc, value_punc)) \ .setParseAction(self._value) families =(family + ZeroOrMore( Literal(',') + family) ).setParseAction(self._families) point_sizes =(size + ZeroOrMore( Literal(',') + size) ).setParseAction(self._point_sizes) property =( (name + Suppress(Literal('=')) + value + ZeroOrMore( Suppress(Literal(',')) + value) ) | name ).setParseAction(self._property) pattern =(Optional( families) + Optional( Literal('-') + point_sizes) + ZeroOrMore( Literal(':') + property) + StringEnd() ) self._parser = pattern self.ParseException = ParseException def parse(self, pattern): """ Parse the given fontconfig *pattern* and return a dictionary of key/value pairs useful for initializing a :class:`font_manager.FontProperties` object. """ props = self._properties = {} try: self._parser.parseString(pattern) except self.ParseException as e: raise ValueError( "Could not parse font string: '%s'\n%s" % (pattern, e)) self._properties = None self._parser.resetCache() return props def _family(self, s, loc, tokens): return [family_unescape(r'\1', str(tokens[0]))] def _size(self, s, loc, tokens): return [float(tokens[0])] def _name(self, s, loc, tokens): return [str(tokens[0])] def _value(self, s, loc, tokens): return [value_unescape(r'\1', str(tokens[0]))] def _families(self, s, loc, tokens): self._properties['family'] = [str(x) for x in tokens] return [] def _point_sizes(self, s, loc, tokens): self._properties['size'] = [str(x) for x in tokens] return [] def _property(self, s, loc, tokens): if len(tokens) == 1: if tokens[0] in self._constants: key, val = self._constants[tokens[0]] self._properties.setdefault(key, []).append(val) else: key = tokens[0] val = tokens[1:] self._properties.setdefault(key, []).extend(val) return [] # `parse_fontconfig_pattern` is a bottleneck during the tests because it is # repeatedly called when the rcParams are reset (to validate the default # fonts). In practice, the cache size doesn't grow beyond a few dozen entries # during the test suite. parse_fontconfig_pattern = lru_cache()(FontconfigPatternParser().parse) def generate_fontconfig_pattern(d): """ Given a dictionary of key/value pairs, generates a fontconfig pattern string. """ props = [] families = '' size = '' for key in 'family style variant weight stretch file size'.split(): val = getattr(d, 'get_' + key)() if val is not None and val != []: if type(val) == list: val = [value_escape(r'\\\1', str(x)) for x in val if x is not None] if val != []: val = ','.join(val) props.append(":%s=%s" % (key, val)) return ''.join(props)
6,800
33.522843
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/mathtext.py
r""" :mod:`~matplotlib.mathtext` is a module for parsing a subset of the TeX math syntax and drawing them to a matplotlib backend. For a tutorial of its usage see :ref:`sphx_glr_tutorials_text_mathtext.py`. This document is primarily concerned with implementation details. The module uses pyparsing_ to parse the TeX expression. .. _pyparsing: http://pyparsing.wikispaces.com/ The Bakoma distribution of the TeX Computer Modern fonts, and STIX fonts are supported. There is experimental support for using arbitrary fonts, but results may vary without proper tweaking and metrics for those fonts. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six import unichr import os from math import ceil import unicodedata from warnings import warn from numpy import inf, isinf import numpy as np from pyparsing import ( Combine, Empty, FollowedBy, Forward, Group, Literal, oneOf, OneOrMore, Optional, ParseBaseException, ParseFatalException, ParserElement, QuotedString, Regex, StringEnd, Suppress, ZeroOrMore) ParserElement.enablePackrat() from matplotlib import _png, colors as mcolors, get_data_path, rcParams from matplotlib.afm import AFM from matplotlib.cbook import Bunch, get_realpath_and_stat, maxdict from matplotlib.ft2font import FT2Image, KERNING_DEFAULT, LOAD_NO_HINTING from matplotlib.font_manager import findfont, FontProperties, get_font from matplotlib._mathtext_data import (latex_to_bakoma, latex_to_standard, tex2uni, latex_to_cmex, stix_virtual_fonts) #################### ############################################################################## # FONTS def get_unicode_index(symbol, math=True): """get_unicode_index(symbol, [bool]) -> integer Return the integer index (from the Unicode table) of symbol. *symbol* can be a single unicode character, a TeX command (i.e. r'\\pi'), or a Type1 symbol name (i.e. 'phi'). If math is False, the current symbol should be treated as a non-math symbol. """ # for a non-math symbol, simply return its unicode index if not math: return ord(symbol) # From UTF #25: U+2212 minus sign is the preferred # representation of the unary and binary minus sign rather than # the ASCII-derived U+002D hyphen-minus, because minus sign is # unambiguous and because it is rendered with a more desirable # length, usually longer than a hyphen. if symbol == '-': return 0x2212 try:# This will succeed if symbol is a single unicode char return ord(symbol) except TypeError: pass try:# Is symbol a TeX symbol (i.e. \alpha) return tex2uni[symbol.strip("\\")] except KeyError: message = """'%(symbol)s' is not a valid Unicode character or TeX/Type1 symbol"""%locals() raise ValueError(message) def unichr_safe(index): """Return the Unicode character corresponding to the index, or the replacement character if this is a narrow build of Python and the requested character is outside the BMP.""" try: return unichr(index) except ValueError: return unichr(0xFFFD) class MathtextBackend(object): """ The base class for the mathtext backend-specific code. The purpose of :class:`MathtextBackend` subclasses is to interface between mathtext and a specific matplotlib graphics backend. Subclasses need to override the following: - :meth:`render_glyph` - :meth:`render_rect_filled` - :meth:`get_results` And optionally, if you need to use a FreeType hinting style: - :meth:`get_hinting_type` """ def __init__(self): self.width = 0 self.height = 0 self.depth = 0 def set_canvas_size(self, w, h, d): 'Dimension the drawing canvas' self.width = w self.height = h self.depth = d def render_glyph(self, ox, oy, info): """ Draw a glyph described by *info* to the reference point (*ox*, *oy*). """ raise NotImplementedError() def render_rect_filled(self, x1, y1, x2, y2): """ Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*). """ raise NotImplementedError() def get_results(self, box): """ Return a backend-specific tuple to return to the backend after all processing is done. """ raise NotImplementedError() def get_hinting_type(self): """ Get the FreeType hinting type to use with this particular backend. """ return LOAD_NO_HINTING class MathtextBackendAgg(MathtextBackend): """ Render glyphs and rectangles to an FTImage buffer, which is later transferred to the Agg image by the Agg backend. """ def __init__(self): self.ox = 0 self.oy = 0 self.image = None self.mode = 'bbox' self.bbox = [0, 0, 0, 0] MathtextBackend.__init__(self) def _update_bbox(self, x1, y1, x2, y2): self.bbox = [min(self.bbox[0], x1), min(self.bbox[1], y1), max(self.bbox[2], x2), max(self.bbox[3], y2)] def set_canvas_size(self, w, h, d): MathtextBackend.set_canvas_size(self, w, h, d) if self.mode != 'bbox': self.image = FT2Image(ceil(w), ceil(h + max(d, 0))) def render_glyph(self, ox, oy, info): if self.mode == 'bbox': self._update_bbox(ox + info.metrics.xmin, oy - info.metrics.ymax, ox + info.metrics.xmax, oy - info.metrics.ymin) else: info.font.draw_glyph_to_bitmap( self.image, ox, oy - info.metrics.iceberg, info.glyph, antialiased=rcParams['text.antialiased']) def render_rect_filled(self, x1, y1, x2, y2): if self.mode == 'bbox': self._update_bbox(x1, y1, x2, y2) else: height = max(int(y2 - y1) - 1, 0) if height == 0: center = (y2 + y1) / 2.0 y = int(center - (height + 1) / 2.0) else: y = int(y1) self.image.draw_rect_filled(int(x1), y, ceil(x2), y + height) def get_results(self, box, used_characters): self.mode = 'bbox' orig_height = box.height orig_depth = box.depth ship(0, 0, box) bbox = self.bbox bbox = [bbox[0] - 1, bbox[1] - 1, bbox[2] + 1, bbox[3] + 1] self.mode = 'render' self.set_canvas_size( bbox[2] - bbox[0], (bbox[3] - bbox[1]) - orig_depth, (bbox[3] - bbox[1]) - orig_height) ship(-bbox[0], -bbox[1], box) result = (self.ox, self.oy, self.width, self.height + self.depth, self.depth, self.image, used_characters) self.image = None return result def get_hinting_type(self): from matplotlib.backends import backend_agg return backend_agg.get_hinting_flag() class MathtextBackendBitmap(MathtextBackendAgg): def get_results(self, box, used_characters): ox, oy, width, height, depth, image, characters = \ MathtextBackendAgg.get_results(self, box, used_characters) return image, depth class MathtextBackendPs(MathtextBackend): """ Store information to write a mathtext rendering to the PostScript backend. """ def __init__(self): self.pswriter = six.moves.cStringIO() self.lastfont = None def render_glyph(self, ox, oy, info): oy = self.height - oy + info.offset postscript_name = info.postscript_name fontsize = info.fontsize symbol_name = info.symbol_name if (postscript_name, fontsize) != self.lastfont: ps = """/%(postscript_name)s findfont %(fontsize)s scalefont setfont """ % locals() self.lastfont = postscript_name, fontsize self.pswriter.write(ps) ps = """%(ox)f %(oy)f moveto /%(symbol_name)s glyphshow\n """ % locals() self.pswriter.write(ps) def render_rect_filled(self, x1, y1, x2, y2): ps = "%f %f %f %f rectfill\n" % (x1, self.height - y2, x2 - x1, y2 - y1) self.pswriter.write(ps) def get_results(self, box, used_characters): ship(0, 0, box) return (self.width, self.height + self.depth, self.depth, self.pswriter, used_characters) class MathtextBackendPdf(MathtextBackend): """ Store information to write a mathtext rendering to the PDF backend. """ def __init__(self): self.glyphs = [] self.rects = [] def render_glyph(self, ox, oy, info): filename = info.font.fname oy = self.height - oy + info.offset self.glyphs.append( (ox, oy, filename, info.fontsize, info.num, info.symbol_name)) def render_rect_filled(self, x1, y1, x2, y2): self.rects.append((x1, self.height - y2, x2 - x1, y2 - y1)) def get_results(self, box, used_characters): ship(0, 0, box) return (self.width, self.height + self.depth, self.depth, self.glyphs, self.rects, used_characters) class MathtextBackendSvg(MathtextBackend): """ Store information to write a mathtext rendering to the SVG backend. """ def __init__(self): self.svg_glyphs = [] self.svg_rects = [] def render_glyph(self, ox, oy, info): oy = self.height - oy + info.offset self.svg_glyphs.append( (info.font, info.fontsize, info.num, ox, oy, info.metrics)) def render_rect_filled(self, x1, y1, x2, y2): self.svg_rects.append( (x1, self.height - y1 + 1, x2 - x1, y2 - y1)) def get_results(self, box, used_characters): ship(0, 0, box) svg_elements = Bunch(svg_glyphs = self.svg_glyphs, svg_rects = self.svg_rects) return (self.width, self.height + self.depth, self.depth, svg_elements, used_characters) class MathtextBackendPath(MathtextBackend): """ Store information to write a mathtext rendering to the text path machinery. """ def __init__(self): self.glyphs = [] self.rects = [] def render_glyph(self, ox, oy, info): oy = self.height - oy + info.offset thetext = info.num self.glyphs.append( (info.font, info.fontsize, thetext, ox, oy)) def render_rect_filled(self, x1, y1, x2, y2): self.rects.append( (x1, self.height-y2 , x2 - x1, y2 - y1)) def get_results(self, box, used_characters): ship(0, 0, box) return (self.width, self.height + self.depth, self.depth, self.glyphs, self.rects) class MathtextBackendCairo(MathtextBackend): """ Store information to write a mathtext rendering to the Cairo backend. """ def __init__(self): self.glyphs = [] self.rects = [] def render_glyph(self, ox, oy, info): oy = oy - info.offset - self.height thetext = unichr_safe(info.num) self.glyphs.append( (info.font, info.fontsize, thetext, ox, oy)) def render_rect_filled(self, x1, y1, x2, y2): self.rects.append( (x1, y1 - self.height, x2 - x1, y2 - y1)) def get_results(self, box, used_characters): ship(0, 0, box) return (self.width, self.height + self.depth, self.depth, self.glyphs, self.rects) class Fonts(object): """ An abstract base class for a system of fonts to use for mathtext. The class must be able to take symbol keys and font file names and return the character metrics. It also delegates to a backend class to do the actual drawing. """ def __init__(self, default_font_prop, mathtext_backend): """ *default_font_prop*: A :class:`~matplotlib.font_manager.FontProperties` object to use for the default non-math font, or the base font for Unicode (generic) font rendering. *mathtext_backend*: A subclass of :class:`MathTextBackend` used to delegate the actual rendering. """ self.default_font_prop = default_font_prop self.mathtext_backend = mathtext_backend self.used_characters = {} def destroy(self): """ Fix any cyclical references before the object is about to be destroyed. """ self.used_characters = None def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): """ Get the kerning distance for font between *sym1* and *sym2*. *fontX*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default/regular (non-math) *fontclassX*: TODO *symX*: a symbol in raw TeX form. e.g., '1', 'x' or '\\sigma' *fontsizeX*: the fontsize in points *dpi*: the current dots-per-inch """ return 0. def get_metrics(self, font, font_class, sym, fontsize, dpi, math=True): """ *font*: one of the TeX font names:: tt, it, rm, cal, sf, bf or default/regular (non-math) *font_class*: TODO *sym*: a symbol in raw TeX form. e.g., '1', 'x' or '\\sigma' *fontsize*: font size in points *dpi*: current dots-per-inch *math*: whether sym is a math character Returns an object with the following attributes: - *advance*: The advance distance (in points) of the glyph. - *height*: The height of the glyph in points. - *width*: The width of the glyph in points. - *xmin*, *xmax*, *ymin*, *ymax* - the ink rectangle of the glyph - *iceberg* - the distance from the baseline to the top of the glyph. This corresponds to TeX's definition of "height". """ info = self._get_info(font, font_class, sym, fontsize, dpi, math) return info.metrics def set_canvas_size(self, w, h, d): """ Set the size of the buffer used to render the math expression. Only really necessary for the bitmap backends. """ self.width, self.height, self.depth = ceil(w), ceil(h), ceil(d) self.mathtext_backend.set_canvas_size(self.width, self.height, self.depth) def render_glyph(self, ox, oy, facename, font_class, sym, fontsize, dpi): """ Draw a glyph at - *ox*, *oy*: position - *facename*: One of the TeX face names - *font_class*: - *sym*: TeX symbol name or single character - *fontsize*: fontsize in points - *dpi*: The dpi to draw at. """ info = self._get_info(facename, font_class, sym, fontsize, dpi) realpath, stat_key = get_realpath_and_stat(info.font.fname) used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].add(info.num) self.mathtext_backend.render_glyph(ox, oy, info) def render_rect_filled(self, x1, y1, x2, y2): """ Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*). """ self.mathtext_backend.render_rect_filled(x1, y1, x2, y2) def get_xheight(self, font, fontsize, dpi): """ Get the xheight for the given *font* and *fontsize*. """ raise NotImplementedError() def get_underline_thickness(self, font, fontsize, dpi): """ Get the line thickness that matches the given font. Used as a base unit for drawing lines such as in a fraction or radical. """ raise NotImplementedError() def get_used_characters(self): """ Get the set of characters that were used in the math expression. Used by backends that need to subset fonts so they know which glyphs to include. """ return self.used_characters def get_results(self, box): """ Get the data needed by the backend to render the math expression. The return value is backend-specific. """ result = self.mathtext_backend.get_results(box, self.get_used_characters()) self.destroy() return result def get_sized_alternatives_for_symbol(self, fontname, sym): """ Override if your font provides multiple sizes of the same symbol. Should return a list of symbols matching *sym* in various sizes. The expression renderer will select the most appropriate size for a given situation from this list. """ return [(fontname, sym)] class TruetypeFonts(Fonts): """ A generic base class for all font setups that use Truetype fonts (through FT2Font). """ def __init__(self, default_font_prop, mathtext_backend): Fonts.__init__(self, default_font_prop, mathtext_backend) self.glyphd = {} self._fonts = {} filename = findfont(default_font_prop) default_font = get_font(filename) self._fonts['default'] = default_font self._fonts['regular'] = default_font def destroy(self): self.glyphd = None Fonts.destroy(self) def _get_font(self, font): if font in self.fontmap: basename = self.fontmap[font] else: basename = font cached_font = self._fonts.get(basename) if cached_font is None and os.path.exists(basename): cached_font = get_font(basename) self._fonts[basename] = cached_font self._fonts[cached_font.postscript_name] = cached_font self._fonts[cached_font.postscript_name.lower()] = cached_font return cached_font def _get_offset(self, font, glyph, fontsize, dpi): if font.postscript_name == 'Cmex10': return ((glyph.height/64.0/2.0) + (fontsize/3.0 * dpi/72.0)) return 0. def _get_info(self, fontname, font_class, sym, fontsize, dpi, math=True): key = fontname, font_class, sym, fontsize, dpi bunch = self.glyphd.get(key) if bunch is not None: return bunch font, num, symbol_name, fontsize, slanted = \ self._get_glyph(fontname, font_class, sym, fontsize, math) font.set_size(fontsize, dpi) glyph = font.load_char( num, flags=self.mathtext_backend.get_hinting_type()) xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox] offset = self._get_offset(font, glyph, fontsize, dpi) metrics = Bunch( advance = glyph.linearHoriAdvance/65536.0, height = glyph.height/64.0, width = glyph.width/64.0, xmin = xmin, xmax = xmax, ymin = ymin+offset, ymax = ymax+offset, # iceberg is the equivalent of TeX's "height" iceberg = glyph.horiBearingY/64.0 + offset, slanted = slanted ) result = self.glyphd[key] = Bunch( font = font, fontsize = fontsize, postscript_name = font.postscript_name, metrics = metrics, symbol_name = symbol_name, num = num, glyph = glyph, offset = offset ) return result def get_xheight(self, fontname, fontsize, dpi): font = self._get_font(fontname) font.set_size(fontsize, dpi) pclt = font.get_sfnt_table('pclt') if pclt is None: # Some fonts don't store the xHeight, so we do a poor man's xHeight metrics = self.get_metrics(fontname, rcParams['mathtext.default'], 'x', fontsize, dpi) return metrics.iceberg xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0) * (dpi / 100.0) return xHeight def get_underline_thickness(self, font, fontsize, dpi): # This function used to grab underline thickness from the font # metrics, but that information is just too un-reliable, so it # is now hardcoded. return ((0.75 / 12.0) * fontsize * dpi) / 72.0 def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): if font1 == font2 and fontsize1 == fontsize2: info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) font = info1.font return font.get_kerning(info1.num, info2.num, KERNING_DEFAULT) / 64.0 return Fonts.get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi) class BakomaFonts(TruetypeFonts): """ Use the Bakoma TrueType fonts for rendering. Symbols are strewn about a number of font files, each of which has its own proprietary 8-bit encoding. """ _fontmap = { 'cal' : 'cmsy10', 'rm' : 'cmr10', 'tt' : 'cmtt10', 'it' : 'cmmi10', 'bf' : 'cmb10', 'sf' : 'cmss10', 'ex' : 'cmex10' } def __init__(self, *args, **kwargs): self._stix_fallback = StixFonts(*args, **kwargs) TruetypeFonts.__init__(self, *args, **kwargs) self.fontmap = {} for key, val in six.iteritems(self._fontmap): fullpath = findfont(val) self.fontmap[key] = fullpath self.fontmap[val] = fullpath _slanted_symbols = set(r"\int \oint".split()) def _get_glyph(self, fontname, font_class, sym, fontsize, math=True): symbol_name = None font = None if fontname in self.fontmap and sym in latex_to_bakoma: basename, num = latex_to_bakoma[sym] slanted = (basename == "cmmi10") or sym in self._slanted_symbols font = self._get_font(basename) elif len(sym) == 1: slanted = (fontname == "it") font = self._get_font(fontname) if font is not None: num = ord(sym) if font is not None: gid = font.get_char_index(num) if gid != 0: symbol_name = font.get_glyph_name(gid) if symbol_name is None: return self._stix_fallback._get_glyph( fontname, font_class, sym, fontsize, math) return font, num, symbol_name, fontsize, slanted # The Bakoma fonts contain many pre-sized alternatives for the # delimiters. The AutoSizedChar class will use these alternatives # and select the best (closest sized) glyph. _size_alternatives = { '(' : [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'), ('ex', '\xb5'), ('ex', '\xc3')], ')' : [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'), ('ex', '\xb6'), ('ex', '\x21')], '{' : [('cal', '{'), ('ex', '\xa9'), ('ex', '\x6e'), ('ex', '\xbd'), ('ex', '\x28')], '}' : [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'), ('ex', '\xbe'), ('ex', '\x29')], # The fourth size of '[' is mysteriously missing from the BaKoMa # font, so I've omitted it for both '[' and ']' '[' : [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'), ('ex', '\x22')], ']' : [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'), ('ex', '\x23')], r'\lfloor' : [('ex', '\xa5'), ('ex', '\x6a'), ('ex', '\xb9'), ('ex', '\x24')], r'\rfloor' : [('ex', '\xa6'), ('ex', '\x6b'), ('ex', '\xba'), ('ex', '\x25')], r'\lceil' : [('ex', '\xa7'), ('ex', '\x6c'), ('ex', '\xbb'), ('ex', '\x26')], r'\rceil' : [('ex', '\xa8'), ('ex', '\x6d'), ('ex', '\xbc'), ('ex', '\x27')], r'\langle' : [('ex', '\xad'), ('ex', '\x44'), ('ex', '\xbf'), ('ex', '\x2a')], r'\rangle' : [('ex', '\xae'), ('ex', '\x45'), ('ex', '\xc0'), ('ex', '\x2b')], r'\__sqrt__' : [('ex', '\x70'), ('ex', '\x71'), ('ex', '\x72'), ('ex', '\x73')], r'\backslash': [('ex', '\xb2'), ('ex', '\x2f'), ('ex', '\xc2'), ('ex', '\x2d')], r'/' : [('rm', '/'), ('ex', '\xb1'), ('ex', '\x2e'), ('ex', '\xcb'), ('ex', '\x2c')], r'\widehat' : [('rm', '\x5e'), ('ex', '\x62'), ('ex', '\x63'), ('ex', '\x64')], r'\widetilde': [('rm', '\x7e'), ('ex', '\x65'), ('ex', '\x66'), ('ex', '\x67')], r'<' : [('cal', 'h'), ('ex', 'D')], r'>' : [('cal', 'i'), ('ex', 'E')] } for alias, target in [(r'\leftparen', '('), (r'\rightparent', ')'), (r'\leftbrace', '{'), (r'\rightbrace', '}'), (r'\leftbracket', '['), (r'\rightbracket', ']'), (r'\{', '{'), (r'\}', '}'), (r'\[', '['), (r'\]', ']')]: _size_alternatives[alias] = _size_alternatives[target] def get_sized_alternatives_for_symbol(self, fontname, sym): return self._size_alternatives.get(sym, [(fontname, sym)]) class UnicodeFonts(TruetypeFonts): """ An abstract base class for handling Unicode fonts. While some reasonably complete Unicode fonts (such as DejaVu) may work in some situations, the only Unicode font I'm aware of with a complete set of math symbols is STIX. This class will "fallback" on the Bakoma fonts when a required symbol can not be found in the font. """ use_cmex = True def __init__(self, *args, **kwargs): # This must come first so the backend's owner is set correctly if rcParams['mathtext.fallback_to_cm']: self.cm_fallback = BakomaFonts(*args, **kwargs) else: self.cm_fallback = None TruetypeFonts.__init__(self, *args, **kwargs) self.fontmap = {} for texfont in "cal rm tt it bf sf".split(): prop = rcParams['mathtext.' + texfont] font = findfont(prop) self.fontmap[texfont] = font prop = FontProperties('cmex10') font = findfont(prop) self.fontmap['ex'] = font _slanted_symbols = set(r"\int \oint".split()) def _map_virtual_font(self, fontname, font_class, uniindex): return fontname, uniindex def _get_glyph(self, fontname, font_class, sym, fontsize, math=True): found_symbol = False if self.use_cmex: uniindex = latex_to_cmex.get(sym) if uniindex is not None: fontname = 'ex' found_symbol = True if not found_symbol: try: uniindex = get_unicode_index(sym, math) found_symbol = True except ValueError: uniindex = ord('?') warn("No TeX to unicode mapping for '%s'" % sym.encode('ascii', 'backslashreplace'), MathTextWarning) fontname, uniindex = self._map_virtual_font( fontname, font_class, uniindex) new_fontname = fontname # Only characters in the "Letter" class should be italicized in 'it' # mode. Greek capital letters should be Roman. if found_symbol: if fontname == 'it': if uniindex < 0x10000: unistring = unichr(uniindex) if (not unicodedata.category(unistring)[0] == "L" or unicodedata.name(unistring).startswith("GREEK CAPITAL")): new_fontname = 'rm' slanted = (new_fontname == 'it') or sym in self._slanted_symbols found_symbol = False font = self._get_font(new_fontname) if font is not None: glyphindex = font.get_char_index(uniindex) if glyphindex != 0: found_symbol = True if not found_symbol: if self.cm_fallback: if isinstance(self.cm_fallback, BakomaFonts): warn("Substituting with a symbol from Computer Modern.", MathTextWarning) if (fontname in ('it', 'regular') and isinstance(self.cm_fallback, StixFonts)): return self.cm_fallback._get_glyph( 'rm', font_class, sym, fontsize) else: return self.cm_fallback._get_glyph( fontname, font_class, sym, fontsize) else: if fontname in ('it', 'regular') and isinstance(self, StixFonts): return self._get_glyph('rm', font_class, sym, fontsize) warn("Font '%s' does not have a glyph for '%s' [U+%x]" % (new_fontname, sym.encode('ascii', 'backslashreplace').decode('ascii'), uniindex), MathTextWarning) warn("Substituting with a dummy symbol.", MathTextWarning) fontname = 'rm' new_fontname = fontname font = self._get_font(fontname) uniindex = 0xA4 # currency character, for lack of anything better glyphindex = font.get_char_index(uniindex) slanted = False symbol_name = font.get_glyph_name(glyphindex) return font, uniindex, symbol_name, fontsize, slanted def get_sized_alternatives_for_symbol(self, fontname, sym): if self.cm_fallback: return self.cm_fallback.get_sized_alternatives_for_symbol( fontname, sym) return [(fontname, sym)] class DejaVuFonts(UnicodeFonts): use_cmex = False def __init__(self, *args, **kwargs): # This must come first so the backend's owner is set correctly if isinstance(self, DejaVuSerifFonts): self.cm_fallback = StixFonts(*args, **kwargs) else: self.cm_fallback = StixSansFonts(*args, **kwargs) self.bakoma = BakomaFonts(*args, **kwargs) TruetypeFonts.__init__(self, *args, **kwargs) self.fontmap = {} # Include Stix sized alternatives for glyphs self._fontmap.update({ 1 : 'STIXSizeOneSym', 2 : 'STIXSizeTwoSym', 3 : 'STIXSizeThreeSym', 4 : 'STIXSizeFourSym', 5 : 'STIXSizeFiveSym'}) for key, name in six.iteritems(self._fontmap): fullpath = findfont(name) self.fontmap[key] = fullpath self.fontmap[name] = fullpath def _get_glyph(self, fontname, font_class, sym, fontsize, math=True): """ Override prime symbol to use Bakoma """ if sym == r'\prime': return self.bakoma._get_glyph(fontname, font_class, sym, fontsize, math) else: # check whether the glyph is available in the display font uniindex = get_unicode_index(sym) font = self._get_font('ex') if font is not None: glyphindex = font.get_char_index(uniindex) if glyphindex != 0: return super(DejaVuFonts, self)._get_glyph('ex', font_class, sym, fontsize, math) # otherwise return regular glyph return super(DejaVuFonts, self)._get_glyph(fontname, font_class, sym, fontsize, math) class DejaVuSerifFonts(DejaVuFonts): """ A font handling class for the DejaVu Serif fonts If a glyph is not found it will fallback to Stix Serif """ _fontmap = { 'rm' : 'DejaVu Serif', 'it' : 'DejaVu Serif:italic', 'bf' : 'DejaVu Serif:weight=bold', 'sf' : 'DejaVu Sans', 'tt' : 'DejaVu Sans Mono', 'ex' : 'DejaVu Serif Display', 0 : 'DejaVu Serif', } class DejaVuSansFonts(DejaVuFonts): """ A font handling class for the DejaVu Sans fonts If a glyph is not found it will fallback to Stix Sans """ _fontmap = { 'rm' : 'DejaVu Sans', 'it' : 'DejaVu Sans:italic', 'bf' : 'DejaVu Sans:weight=bold', 'sf' : 'DejaVu Sans', 'tt' : 'DejaVu Sans Mono', 'ex' : 'DejaVu Sans Display', 0 : 'DejaVu Sans', } class StixFonts(UnicodeFonts): """ A font handling class for the STIX fonts. In addition to what UnicodeFonts provides, this class: - supports "virtual fonts" which are complete alpha numeric character sets with different font styles at special Unicode code points, such as "Blackboard". - handles sized alternative characters for the STIXSizeX fonts. """ _fontmap = { 'rm' : 'STIXGeneral', 'it' : 'STIXGeneral:italic', 'bf' : 'STIXGeneral:weight=bold', 'nonunirm' : 'STIXNonUnicode', 'nonuniit' : 'STIXNonUnicode:italic', 'nonunibf' : 'STIXNonUnicode:weight=bold', 0 : 'STIXGeneral', 1 : 'STIXSizeOneSym', 2 : 'STIXSizeTwoSym', 3 : 'STIXSizeThreeSym', 4 : 'STIXSizeFourSym', 5 : 'STIXSizeFiveSym' } use_cmex = False cm_fallback = False _sans = False def __init__(self, *args, **kwargs): TruetypeFonts.__init__(self, *args, **kwargs) self.fontmap = {} for key, name in six.iteritems(self._fontmap): fullpath = findfont(name) self.fontmap[key] = fullpath self.fontmap[name] = fullpath def _map_virtual_font(self, fontname, font_class, uniindex): # Handle these "fonts" that are actually embedded in # other fonts. mapping = stix_virtual_fonts.get(fontname) if (self._sans and mapping is None and fontname not in ('regular', 'default')): mapping = stix_virtual_fonts['sf'] doing_sans_conversion = True else: doing_sans_conversion = False if mapping is not None: if isinstance(mapping, dict): try: mapping = mapping[font_class] except KeyError: mapping = mapping['rm'] # Binary search for the source glyph lo = 0 hi = len(mapping) while lo < hi: mid = (lo+hi)//2 range = mapping[mid] if uniindex < range[0]: hi = mid elif uniindex <= range[1]: break else: lo = mid + 1 if uniindex >= range[0] and uniindex <= range[1]: uniindex = uniindex - range[0] + range[3] fontname = range[2] elif not doing_sans_conversion: # This will generate a dummy character uniindex = 0x1 fontname = rcParams['mathtext.default'] # Handle private use area glyphs if (fontname in ('it', 'rm', 'bf') and uniindex >= 0xe000 and uniindex <= 0xf8ff): fontname = 'nonuni' + fontname return fontname, uniindex _size_alternatives = {} def get_sized_alternatives_for_symbol(self, fontname, sym): fixes = {'\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']'} sym = fixes.get(sym, sym) alternatives = self._size_alternatives.get(sym) if alternatives: return alternatives alternatives = [] try: uniindex = get_unicode_index(sym) except ValueError: return [(fontname, sym)] fix_ups = { ord('<'): 0x27e8, ord('>'): 0x27e9 } uniindex = fix_ups.get(uniindex, uniindex) for i in range(6): font = self._get_font(i) glyphindex = font.get_char_index(uniindex) if glyphindex != 0: alternatives.append((i, unichr_safe(uniindex))) # The largest size of the radical symbol in STIX has incorrect # metrics that cause it to be disconnected from the stem. if sym == r'\__sqrt__': alternatives = alternatives[:-1] self._size_alternatives[sym] = alternatives return alternatives class StixSansFonts(StixFonts): """ A font handling class for the STIX fonts (that uses sans-serif characters by default). """ _sans = True class StandardPsFonts(Fonts): """ Use the standard postscript fonts for rendering to backend_ps Unlike the other font classes, BakomaFont and UnicodeFont, this one requires the Ps backend. """ basepath = os.path.join( get_data_path(), 'fonts', 'afm' ) fontmap = { 'cal' : 'pzcmi8a', # Zapf Chancery 'rm' : 'pncr8a', # New Century Schoolbook 'tt' : 'pcrr8a', # Courier 'it' : 'pncri8a', # New Century Schoolbook Italic 'sf' : 'phvr8a', # Helvetica 'bf' : 'pncb8a', # New Century Schoolbook Bold None : 'psyr' # Symbol } def __init__(self, default_font_prop): Fonts.__init__(self, default_font_prop, MathtextBackendPs()) self.glyphd = {} self.fonts = {} filename = findfont(default_font_prop, fontext='afm', directory=self.basepath) if filename is None: filename = findfont('Helvetica', fontext='afm', directory=self.basepath) with open(filename, 'rb') as fd: default_font = AFM(fd) default_font.fname = filename self.fonts['default'] = default_font self.fonts['regular'] = default_font self.pswriter = six.moves.cStringIO() def _get_font(self, font): if font in self.fontmap: basename = self.fontmap[font] else: basename = font cached_font = self.fonts.get(basename) if cached_font is None: fname = os.path.join(self.basepath, basename + ".afm") with open(fname, 'rb') as fd: cached_font = AFM(fd) cached_font.fname = fname self.fonts[basename] = cached_font self.fonts[cached_font.get_fontname()] = cached_font return cached_font def _get_info (self, fontname, font_class, sym, fontsize, dpi, math=True): 'load the cmfont, metrics and glyph with caching' key = fontname, sym, fontsize, dpi tup = self.glyphd.get(key) if tup is not None: return tup # Only characters in the "Letter" class should really be italicized. # This class includes greek letters, so we're ok if (fontname == 'it' and (len(sym) > 1 or not unicodedata.category(six.text_type(sym)).startswith("L"))): fontname = 'rm' found_symbol = False if sym in latex_to_standard: fontname, num = latex_to_standard[sym] glyph = chr(num) found_symbol = True elif len(sym) == 1: glyph = sym num = ord(glyph) found_symbol = True else: warn("No TeX to built-in Postscript mapping for {!r}".format(sym), MathTextWarning) slanted = (fontname == 'it') font = self._get_font(fontname) if found_symbol: try: symbol_name = font.get_name_char(glyph) except KeyError: warn("No glyph in standard Postscript font {!r} for {!r}" .format(font.get_fontname(), sym), MathTextWarning) found_symbol = False if not found_symbol: glyph = sym = '?' num = ord(glyph) symbol_name = font.get_name_char(glyph) offset = 0 scale = 0.001 * fontsize xmin, ymin, xmax, ymax = [val * scale for val in font.get_bbox_char(glyph)] metrics = Bunch( advance = font.get_width_char(glyph) * scale, width = font.get_width_char(glyph) * scale, height = font.get_height_char(glyph) * scale, xmin = xmin, xmax = xmax, ymin = ymin+offset, ymax = ymax+offset, # iceberg is the equivalent of TeX's "height" iceberg = ymax + offset, slanted = slanted ) self.glyphd[key] = Bunch( font = font, fontsize = fontsize, postscript_name = font.get_fontname(), metrics = metrics, symbol_name = symbol_name, num = num, glyph = glyph, offset = offset ) return self.glyphd[key] def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): if font1 == font2 and fontsize1 == fontsize2: info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) font = info1.font return (font.get_kern_dist(info1.glyph, info2.glyph) * 0.001 * fontsize1) return Fonts.get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi) def get_xheight(self, font, fontsize, dpi): font = self._get_font(font) return font.get_xheight() * 0.001 * fontsize def get_underline_thickness(self, font, fontsize, dpi): font = self._get_font(font) return font.get_underline_thickness() * 0.001 * fontsize ############################################################################## # TeX-LIKE BOX MODEL # The following is based directly on the document 'woven' from the # TeX82 source code. This information is also available in printed # form: # # Knuth, Donald E.. 1986. Computers and Typesetting, Volume B: # TeX: The Program. Addison-Wesley Professional. # # The most relevant "chapters" are: # Data structures for boxes and their friends # Shipping pages out (Ship class) # Packaging (hpack and vpack) # Data structures for math mode # Subroutines for math mode # Typesetting math formulas # # Many of the docstrings below refer to a numbered "node" in that # book, e.g., node123 # # Note that (as TeX) y increases downward, unlike many other parts of # matplotlib. # How much text shrinks when going to the next-smallest level. GROW_FACTOR # must be the inverse of SHRINK_FACTOR. SHRINK_FACTOR = 0.7 GROW_FACTOR = 1.0 / SHRINK_FACTOR # The number of different sizes of chars to use, beyond which they will not # get any smaller NUM_SIZE_LEVELS = 6 class FontConstantsBase(object): """ A set of constants that controls how certain things, such as sub- and superscripts are laid out. These are all metrics that can't be reliably retrieved from the font metrics in the font itself. """ # Percentage of x-height of additional horiz. space after sub/superscripts script_space = 0.05 # Percentage of x-height that sub/superscripts drop below the baseline subdrop = 0.4 # Percentage of x-height that superscripts are raised from the baseline sup1 = 0.7 # Percentage of x-height that subscripts drop below the baseline sub1 = 0.3 # Percentage of x-height that subscripts drop below the baseline when a # superscript is present sub2 = 0.5 # Percentage of x-height that sub/supercripts are offset relative to the # nucleus edge for non-slanted nuclei delta = 0.025 # Additional percentage of last character height above 2/3 of the # x-height that supercripts are offset relative to the subscript # for slanted nuclei delta_slanted = 0.2 # Percentage of x-height that supercripts and subscripts are offset for # integrals delta_integral = 0.1 class ComputerModernFontConstants(FontConstantsBase): script_space = 0.075 subdrop = 0.2 sup1 = 0.45 sub1 = 0.2 sub2 = 0.3 delta = 0.075 delta_slanted = 0.3 delta_integral = 0.3 class STIXFontConstants(FontConstantsBase): script_space = 0.1 sup1 = 0.8 sub2 = 0.6 delta = 0.05 delta_slanted = 0.3 delta_integral = 0.3 class STIXSansFontConstants(FontConstantsBase): script_space = 0.05 sup1 = 0.8 delta_slanted = 0.6 delta_integral = 0.3 class DejaVuSerifFontConstants(FontConstantsBase): pass class DejaVuSansFontConstants(FontConstantsBase): pass # Maps font family names to the FontConstantBase subclass to use _font_constant_mapping = { 'DejaVu Sans': DejaVuSansFontConstants, 'DejaVu Sans Mono': DejaVuSansFontConstants, 'DejaVu Serif': DejaVuSerifFontConstants, 'cmb10': ComputerModernFontConstants, 'cmex10': ComputerModernFontConstants, 'cmmi10': ComputerModernFontConstants, 'cmr10': ComputerModernFontConstants, 'cmss10': ComputerModernFontConstants, 'cmsy10': ComputerModernFontConstants, 'cmtt10': ComputerModernFontConstants, 'STIXGeneral': STIXFontConstants, 'STIXNonUnicode': STIXFontConstants, 'STIXSizeFiveSym': STIXFontConstants, 'STIXSizeFourSym': STIXFontConstants, 'STIXSizeThreeSym': STIXFontConstants, 'STIXSizeTwoSym': STIXFontConstants, 'STIXSizeOneSym': STIXFontConstants, # Map the fonts we used to ship, just for good measure 'Bitstream Vera Sans': DejaVuSansFontConstants, 'Bitstream Vera': DejaVuSansFontConstants, } def _get_font_constant_set(state): constants = _font_constant_mapping.get( state.font_output._get_font(state.font).family_name, FontConstantsBase) # STIX sans isn't really its own fonts, just different code points # in the STIX fonts, so we have to detect this one separately. if (constants is STIXFontConstants and isinstance(state.font_output, StixSansFonts)): return STIXSansFontConstants return constants class MathTextWarning(Warning): pass class Node(object): """ A node in the TeX box model """ def __init__(self): self.size = 0 def __repr__(self): return self.__internal_repr__() def __internal_repr__(self): return self.__class__.__name__ def get_kerning(self, next): return 0.0 def shrink(self): """ Shrinks one level smaller. There are only three levels of sizes, after which things will no longer get smaller. """ self.size += 1 def grow(self): """ Grows one level larger. There is no limit to how big something can get. """ self.size -= 1 def render(self, x, y): pass class Box(Node): """ Represents any node with a physical location. """ def __init__(self, width, height, depth): Node.__init__(self) self.width = width self.height = height self.depth = depth def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: self.width *= SHRINK_FACTOR self.height *= SHRINK_FACTOR self.depth *= SHRINK_FACTOR def grow(self): Node.grow(self) self.width *= GROW_FACTOR self.height *= GROW_FACTOR self.depth *= GROW_FACTOR def render(self, x1, y1, x2, y2): pass class Vbox(Box): """ A box with only height (zero width). """ def __init__(self, height, depth): Box.__init__(self, 0., height, depth) class Hbox(Box): """ A box with only width (zero height and depth). """ def __init__(self, width): Box.__init__(self, width, 0., 0.) class Char(Node): """ Represents a single character. Unlike TeX, the font information and metrics are stored with each :class:`Char` to make it easier to lookup the font metrics when needed. Note that TeX boxes have a width, height, and depth, unlike Type1 and Truetype which use a full bounding box and an advance in the x-direction. The metrics must be converted to the TeX way, and the advance (if different from width) must be converted into a :class:`Kern` node when the :class:`Char` is added to its parent :class:`Hlist`. """ def __init__(self, c, state, math=True): Node.__init__(self) self.c = c self.font_output = state.font_output self.font = state.font self.font_class = state.font_class self.fontsize = state.fontsize self.dpi = state.dpi self.math = math # The real width, height and depth will be set during the # pack phase, after we know the real fontsize self._update_metrics() def __internal_repr__(self): return '`%s`' % self.c def _update_metrics(self): metrics = self._metrics = self.font_output.get_metrics( self.font, self.font_class, self.c, self.fontsize, self.dpi, self.math) if self.c == ' ': self.width = metrics.advance else: self.width = metrics.width self.height = metrics.iceberg self.depth = -(metrics.iceberg - metrics.height) def is_slanted(self): return self._metrics.slanted def get_kerning(self, next): """ Return the amount of kerning between this and the given character. Called when characters are strung together into :class:`Hlist` to create :class:`Kern` nodes. """ advance = self._metrics.advance - self.width kern = 0. if isinstance(next, Char): kern = self.font_output.get_kern( self.font, self.font_class, self.c, self.fontsize, next.font, next.font_class, next.c, next.fontsize, self.dpi) return advance + kern def render(self, x, y): """ Render the character to the canvas """ self.font_output.render_glyph( x, y, self.font, self.font_class, self.c, self.fontsize, self.dpi) def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: self.fontsize *= SHRINK_FACTOR self.width *= SHRINK_FACTOR self.height *= SHRINK_FACTOR self.depth *= SHRINK_FACTOR def grow(self): Node.grow(self) self.fontsize *= GROW_FACTOR self.width *= GROW_FACTOR self.height *= GROW_FACTOR self.depth *= GROW_FACTOR class Accent(Char): """ The font metrics need to be dealt with differently for accents, since they are already offset correctly from the baseline in TrueType fonts. """ def _update_metrics(self): metrics = self._metrics = self.font_output.get_metrics( self.font, self.font_class, self.c, self.fontsize, self.dpi) self.width = metrics.xmax - metrics.xmin self.height = metrics.ymax - metrics.ymin self.depth = 0 def shrink(self): Char.shrink(self) self._update_metrics() def grow(self): Char.grow(self) self._update_metrics() def render(self, x, y): """ Render the character to the canvas. """ self.font_output.render_glyph( x - self._metrics.xmin, y + self._metrics.ymin, self.font, self.font_class, self.c, self.fontsize, self.dpi) class List(Box): """ A list of nodes (either horizontal or vertical). """ def __init__(self, elements): Box.__init__(self, 0., 0., 0.) self.shift_amount = 0. # An arbitrary offset self.children = elements # The child nodes of this list # The following parameters are set in the vpack and hpack functions self.glue_set = 0. # The glue setting of this list self.glue_sign = 0 # 0: normal, -1: shrinking, 1: stretching self.glue_order = 0 # The order of infinity (0 - 3) for the glue def __repr__(self): return '[%s <%.02f %.02f %.02f %.02f> %s]' % ( self.__internal_repr__(), self.width, self.height, self.depth, self.shift_amount, ' '.join([repr(x) for x in self.children])) def _determine_order(self, totals): """ A helper function to determine the highest order of glue used by the members of this list. Used by vpack and hpack. """ o = 0 for i in range(len(totals) - 1, 0, -1): if totals[i] != 0.0: o = i break return o def _set_glue(self, x, sign, totals, error_type): o = self._determine_order(totals) self.glue_order = o self.glue_sign = sign if totals[o] != 0.: self.glue_set = x / totals[o] else: self.glue_sign = 0 self.glue_ratio = 0. if o == 0: if len(self.children): warn("%s %s: %r" % (error_type, self.__class__.__name__, self), MathTextWarning) def shrink(self): for child in self.children: child.shrink() Box.shrink(self) if self.size < NUM_SIZE_LEVELS: self.shift_amount *= SHRINK_FACTOR self.glue_set *= SHRINK_FACTOR def grow(self): for child in self.children: child.grow() Box.grow(self) self.shift_amount *= GROW_FACTOR self.glue_set *= GROW_FACTOR class Hlist(List): """ A horizontal list of boxes. """ def __init__(self, elements, w=0., m='additional', do_kern=True): List.__init__(self, elements) if do_kern: self.kern() self.hpack() def kern(self): """ Insert :class:`Kern` nodes between :class:`Char` nodes to set kerning. The :class:`Char` nodes themselves determine the amount of kerning they need (in :meth:`~Char.get_kerning`), and this function just creates the linked list in the correct way. """ new_children = [] num_children = len(self.children) if num_children: for i in range(num_children): elem = self.children[i] if i < num_children - 1: next = self.children[i + 1] else: next = None new_children.append(elem) kerning_distance = elem.get_kerning(next) if kerning_distance != 0.: kern = Kern(kerning_distance) new_children.append(kern) self.children = new_children # This is a failed experiment to fake cross-font kerning. # def get_kerning(self, next): # if len(self.children) >= 2 and isinstance(self.children[-2], Char): # if isinstance(next, Char): # print "CASE A" # return self.children[-2].get_kerning(next) # elif isinstance(next, Hlist) and len(next.children) and isinstance(next.children[0], Char): # print "CASE B" # result = self.children[-2].get_kerning(next.children[0]) # print result # return result # return 0.0 def hpack(self, w=0., m='additional'): """ The main duty of :meth:`hpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. The computed sizes normally enclose all of the material inside the new box; but some items may stick out if negative glue is used, if the box is overfull, or if a ``\\vbox`` includes other boxes that have been shifted left. - *w*: specifies a width - *m*: is either 'exactly' or 'additional'. Thus, ``hpack(w, 'exactly')`` produces a box whose width is exactly *w*, while ``hpack(w, 'additional')`` yields a box whose width is the natural width plus *w*. The default values produce a box with the natural width. """ # I don't know why these get reset in TeX. Shift_amount is pretty # much useless if we do. #self.shift_amount = 0. h = 0. d = 0. x = 0. total_stretch = [0.] * 4 total_shrink = [0.] * 4 for p in self.children: if isinstance(p, Char): x += p.width h = max(h, p.height) d = max(d, p.depth) elif isinstance(p, Box): x += p.width if not np.isinf(p.height) and not np.isinf(p.depth): s = getattr(p, 'shift_amount', 0.) h = max(h, p.height - s) d = max(d, p.depth + s) elif isinstance(p, Glue): glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += p.width self.height = h self.depth = d if m == 'additional': w += x self.width = w x = w - x if x == 0.: self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0. return if x > 0.: self._set_glue(x, 1, total_stretch, "Overfull") else: self._set_glue(x, -1, total_shrink, "Underfull") class Vlist(List): """ A vertical list of boxes. """ def __init__(self, elements, h=0., m='additional'): List.__init__(self, elements) self.vpack() def vpack(self, h=0., m='additional', l=np.inf): """ The main duty of :meth:`vpack` is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. - *h*: specifies a height - *m*: is either 'exactly' or 'additional'. - *l*: a maximum height Thus, ``vpack(h, 'exactly')`` produces a box whose height is exactly *h*, while ``vpack(h, 'additional')`` yields a box whose height is the natural height plus *h*. The default values produce a box with the natural width. """ # I don't know why these get reset in TeX. Shift_amount is pretty # much useless if we do. # self.shift_amount = 0. w = 0. d = 0. x = 0. total_stretch = [0.] * 4 total_shrink = [0.] * 4 for p in self.children: if isinstance(p, Box): x += d + p.height d = p.depth if not np.isinf(p.width): s = getattr(p, 'shift_amount', 0.) w = max(w, p.width + s) elif isinstance(p, Glue): x += d d = 0. glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += d + p.width d = 0. elif isinstance(p, Char): raise RuntimeError("Internal mathtext error: Char node found in Vlist.") self.width = w if d > l: x += d - l self.depth = l else: self.depth = d if m == 'additional': h += x self.height = h x = h - x if x == 0: self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0. return if x > 0.: self._set_glue(x, 1, total_stretch, "Overfull") else: self._set_glue(x, -1, total_shrink, "Underfull") class Rule(Box): """ A :class:`Rule` node stands for a solid black rectangle; it has *width*, *depth*, and *height* fields just as in an :class:`Hlist`. However, if any of these dimensions is inf, the actual value will be determined by running the rule up to the boundary of the innermost enclosing box. This is called a "running dimension." The width is never running in an :class:`Hlist`; the height and depth are never running in a :class:`Vlist`. """ def __init__(self, width, height, depth, state): Box.__init__(self, width, height, depth) self.font_output = state.font_output def render(self, x, y, w, h): self.font_output.render_rect_filled(x, y, x + w, y + h) class Hrule(Rule): """ Convenience class to create a horizontal rule. """ def __init__(self, state, thickness=None): if thickness is None: thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) height = depth = thickness * 0.5 Rule.__init__(self, np.inf, height, depth, state) class Vrule(Rule): """ Convenience class to create a vertical rule. """ def __init__(self, state): thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) Rule.__init__(self, thickness, np.inf, np.inf, state) class Glue(Node): """ Most of the information in this object is stored in the underlying :class:`GlueSpec` class, which is shared between multiple glue objects. (This is a memory optimization which probably doesn't matter anymore, but it's easier to stick to what TeX does.) """ def __init__(self, glue_type, copy=False): Node.__init__(self) self.glue_subtype = 'normal' if isinstance(glue_type, six.string_types): glue_spec = GlueSpec.factory(glue_type) elif isinstance(glue_type, GlueSpec): glue_spec = glue_type else: raise ValueError("glue_type must be a glue spec name or instance.") if copy: glue_spec = glue_spec.copy() self.glue_spec = glue_spec def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: if self.glue_spec.width != 0.: self.glue_spec = self.glue_spec.copy() self.glue_spec.width *= SHRINK_FACTOR def grow(self): Node.grow(self) if self.glue_spec.width != 0.: self.glue_spec = self.glue_spec.copy() self.glue_spec.width *= GROW_FACTOR class GlueSpec(object): """ See :class:`Glue`. """ def __init__(self, width=0., stretch=0., stretch_order=0, shrink=0., shrink_order=0): self.width = width self.stretch = stretch self.stretch_order = stretch_order self.shrink = shrink self.shrink_order = shrink_order def copy(self): return GlueSpec( self.width, self.stretch, self.stretch_order, self.shrink, self.shrink_order) def factory(cls, glue_type): return cls._types[glue_type] factory = classmethod(factory) GlueSpec._types = { 'fil': GlueSpec(0., 1., 1, 0., 0), 'fill': GlueSpec(0., 1., 2, 0., 0), 'filll': GlueSpec(0., 1., 3, 0., 0), 'neg_fil': GlueSpec(0., 0., 0, 1., 1), 'neg_fill': GlueSpec(0., 0., 0, 1., 2), 'neg_filll': GlueSpec(0., 0., 0, 1., 3), 'empty': GlueSpec(0., 0., 0, 0., 0), 'ss': GlueSpec(0., 1., 1, -1., 1) } # Some convenient ways to get common kinds of glue class Fil(Glue): def __init__(self): Glue.__init__(self, 'fil') class Fill(Glue): def __init__(self): Glue.__init__(self, 'fill') class Filll(Glue): def __init__(self): Glue.__init__(self, 'filll') class NegFil(Glue): def __init__(self): Glue.__init__(self, 'neg_fil') class NegFill(Glue): def __init__(self): Glue.__init__(self, 'neg_fill') class NegFilll(Glue): def __init__(self): Glue.__init__(self, 'neg_filll') class SsGlue(Glue): def __init__(self): Glue.__init__(self, 'ss') class HCentered(Hlist): """ A convenience class to create an :class:`Hlist` whose contents are centered within its enclosing box. """ def __init__(self, elements): Hlist.__init__(self, [SsGlue()] + elements + [SsGlue()], do_kern=False) class VCentered(Hlist): """ A convenience class to create a :class:`Vlist` whose contents are centered within its enclosing box. """ def __init__(self, elements): Vlist.__init__(self, [SsGlue()] + elements + [SsGlue()]) class Kern(Node): """ A :class:`Kern` node has a width field to specify a (normally negative) amount of spacing. This spacing correction appears in horizontal lists between letters like A and V when the font designer said that it looks better to move them closer together or further apart. A kern node can also appear in a vertical list, when its *width* denotes additional spacing in the vertical direction. """ height = 0 depth = 0 def __init__(self, width): Node.__init__(self) self.width = width def __repr__(self): return "k%.02f" % self.width def shrink(self): Node.shrink(self) if self.size < NUM_SIZE_LEVELS: self.width *= SHRINK_FACTOR def grow(self): Node.grow(self) self.width *= GROW_FACTOR class SubSuperCluster(Hlist): """ :class:`SubSuperCluster` is a sort of hack to get around that fact that this code do a two-pass parse like TeX. This lets us store enough information in the hlist itself, namely the nucleus, sub- and super-script, such that if another script follows that needs to be attached, it can be reconfigured on the fly. """ def __init__(self): self.nucleus = None self.sub = None self.super = None Hlist.__init__(self, []) class AutoHeightChar(Hlist): """ :class:`AutoHeightChar` will create a character as close to the given height and depth as possible. When using a font with multiple height versions of some characters (such as the BaKoMa fonts), the correct glyph will be selected, otherwise this will always just return a scaled version of the glyph. """ def __init__(self, c, height, depth, state, always=False, factor=None): alternatives = state.font_output.get_sized_alternatives_for_symbol( state.font, c) xHeight = state.font_output.get_xheight( state.font, state.fontsize, state.dpi) state = state.copy() target_total = height + depth for fontname, sym in alternatives: state.font = fontname char = Char(sym, state) # Ensure that size 0 is chosen when the text is regular sized but # with descender glyphs by subtracting 0.2 * xHeight if char.height + char.depth >= target_total - 0.2 * xHeight: break shift = 0 if state.font != 0: if factor is None: factor = (target_total) / (char.height + char.depth) state.fontsize *= factor char = Char(sym, state) shift = (depth - char.depth) Hlist.__init__(self, [char]) self.shift_amount = shift class AutoWidthChar(Hlist): """ :class:`AutoWidthChar` will create a character as close to the given width as possible. When using a font with multiple width versions of some characters (such as the BaKoMa fonts), the correct glyph will be selected, otherwise this will always just return a scaled version of the glyph. """ def __init__(self, c, width, state, always=False, char_class=Char): alternatives = state.font_output.get_sized_alternatives_for_symbol( state.font, c) state = state.copy() for fontname, sym in alternatives: state.font = fontname char = char_class(sym, state) if char.width >= width: break factor = width / char.width state.fontsize *= factor char = char_class(sym, state) Hlist.__init__(self, [char]) self.width = char.width class Ship(object): """ Once the boxes have been set up, this sends them to output. Since boxes can be inside of boxes inside of boxes, the main work of :class:`Ship` is done by two mutually recursive routines, :meth:`hlist_out` and :meth:`vlist_out`, which traverse the :class:`Hlist` nodes and :class:`Vlist` nodes inside of horizontal and vertical boxes. The global variables used in TeX to store state as it processes have become member variables here. """ def __call__(self, ox, oy, box): self.max_push = 0 # Deepest nesting of push commands so far self.cur_s = 0 self.cur_v = 0. self.cur_h = 0. self.off_h = ox self.off_v = oy + box.height self.hlist_out(box) def clamp(value): if value < -1000000000.: return -1000000000. if value > 1000000000.: return 1000000000. return value clamp = staticmethod(clamp) def hlist_out(self, box): cur_g = 0 cur_glue = 0. glue_order = box.glue_order glue_sign = box.glue_sign base_line = self.cur_v left_edge = self.cur_h self.cur_s += 1 self.max_push = max(self.cur_s, self.max_push) clamp = self.clamp for p in box.children: if isinstance(p, Char): p.render(self.cur_h + self.off_h, self.cur_v + self.off_v) self.cur_h += p.width elif isinstance(p, Kern): self.cur_h += p.width elif isinstance(p, List): # node623 if len(p.children) == 0: self.cur_h += p.width else: edge = self.cur_h self.cur_v = base_line + p.shift_amount if isinstance(p, Hlist): self.hlist_out(p) else: # p.vpack(box.height + box.depth, 'exactly') self.vlist_out(p) self.cur_h = edge + p.width self.cur_v = base_line elif isinstance(p, Box): # node624 rule_height = p.height rule_depth = p.depth rule_width = p.width if np.isinf(rule_height): rule_height = box.height if np.isinf(rule_depth): rule_depth = box.depth if rule_height > 0 and rule_width > 0: self.cur_v = base_line + rule_depth p.render(self.cur_h + self.off_h, self.cur_v + self.off_v, rule_width, rule_height) self.cur_v = base_line self.cur_h += rule_width elif isinstance(p, Glue): # node625 glue_spec = p.glue_spec rule_width = glue_spec.width - cur_g if glue_sign != 0: # normal if glue_sign == 1: # stretching if glue_spec.stretch_order == glue_order: cur_glue += glue_spec.stretch cur_g = np.round(clamp(float(box.glue_set) * cur_glue)) elif glue_spec.shrink_order == glue_order: cur_glue += glue_spec.shrink cur_g = np.round(clamp(float(box.glue_set) * cur_glue)) rule_width += cur_g self.cur_h += rule_width self.cur_s -= 1 def vlist_out(self, box): cur_g = 0 cur_glue = 0. glue_order = box.glue_order glue_sign = box.glue_sign self.cur_s += 1 self.max_push = max(self.max_push, self.cur_s) left_edge = self.cur_h self.cur_v -= box.height top_edge = self.cur_v clamp = self.clamp for p in box.children: if isinstance(p, Kern): self.cur_v += p.width elif isinstance(p, List): if len(p.children) == 0: self.cur_v += p.height + p.depth else: self.cur_v += p.height self.cur_h = left_edge + p.shift_amount save_v = self.cur_v p.width = box.width if isinstance(p, Hlist): self.hlist_out(p) else: self.vlist_out(p) self.cur_v = save_v + p.depth self.cur_h = left_edge elif isinstance(p, Box): rule_height = p.height rule_depth = p.depth rule_width = p.width if np.isinf(rule_width): rule_width = box.width rule_height += rule_depth if rule_height > 0 and rule_depth > 0: self.cur_v += rule_height p.render(self.cur_h + self.off_h, self.cur_v + self.off_v, rule_width, rule_height) elif isinstance(p, Glue): glue_spec = p.glue_spec rule_height = glue_spec.width - cur_g if glue_sign != 0: # normal if glue_sign == 1: # stretching if glue_spec.stretch_order == glue_order: cur_glue += glue_spec.stretch cur_g = np.round(clamp(float(box.glue_set) * cur_glue)) elif glue_spec.shrink_order == glue_order: # shrinking cur_glue += glue_spec.shrink cur_g = np.round(clamp(float(box.glue_set) * cur_glue)) rule_height += cur_g self.cur_v += rule_height elif isinstance(p, Char): raise RuntimeError("Internal mathtext error: Char node found in vlist") self.cur_s -= 1 ship = Ship() ############################################################################## # PARSER def Error(msg): """ Helper class to raise parser errors. """ def raise_error(s, loc, toks): raise ParseFatalException(s, loc, msg) empty = Empty() empty.setParseAction(raise_error) return empty class Parser(object): """ This is the pyparsing-based parser for math expressions. It actually parses full strings *containing* math expressions, in that raw text may also appear outside of pairs of ``$``. The grammar is based directly on that in TeX, though it cuts a few corners. """ _math_style_dict = dict(displaystyle=0, textstyle=1, scriptstyle=2, scriptscriptstyle=3) _binary_operators = set(''' + * - \\pm \\sqcap \\rhd \\mp \\sqcup \\unlhd \\times \\vee \\unrhd \\div \\wedge \\oplus \\ast \\setminus \\ominus \\star \\wr \\otimes \\circ \\diamond \\oslash \\bullet \\bigtriangleup \\odot \\cdot \\bigtriangledown \\bigcirc \\cap \\triangleleft \\dagger \\cup \\triangleright \\ddagger \\uplus \\lhd \\amalg'''.split()) _relation_symbols = set(''' = < > : \\leq \\geq \\equiv \\models \\prec \\succ \\sim \\perp \\preceq \\succeq \\simeq \\mid \\ll \\gg \\asymp \\parallel \\subset \\supset \\approx \\bowtie \\subseteq \\supseteq \\cong \\Join \\sqsubset \\sqsupset \\neq \\smile \\sqsubseteq \\sqsupseteq \\doteq \\frown \\in \\ni \\propto \\vdash \\dashv \\dots \\dotplus \\doteqdot'''.split()) _arrow_symbols = set(''' \\leftarrow \\longleftarrow \\uparrow \\Leftarrow \\Longleftarrow \\Uparrow \\rightarrow \\longrightarrow \\downarrow \\Rightarrow \\Longrightarrow \\Downarrow \\leftrightarrow \\longleftrightarrow \\updownarrow \\Leftrightarrow \\Longleftrightarrow \\Updownarrow \\mapsto \\longmapsto \\nearrow \\hookleftarrow \\hookrightarrow \\searrow \\leftharpoonup \\rightharpoonup \\swarrow \\leftharpoondown \\rightharpoondown \\nwarrow \\rightleftharpoons \\leadsto'''.split()) _spaced_symbols = _binary_operators | _relation_symbols | _arrow_symbols _punctuation_symbols = set(r', ; . ! \ldotp \cdotp'.split()) _overunder_symbols = set(r''' \sum \prod \coprod \bigcap \bigcup \bigsqcup \bigvee \bigwedge \bigodot \bigotimes \bigoplus \biguplus '''.split()) _overunder_functions = set( r"lim liminf limsup sup max min".split()) _dropsub_symbols = set(r'''\int \oint'''.split()) _fontnames = set("rm cal it tt sf bf default bb frak circled scr regular".split()) _function_names = set(""" arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan coth inf max tanh""".split()) _ambi_delim = set(""" | \\| / \\backslash \\uparrow \\downarrow \\updownarrow \\Uparrow \\Downarrow \\Updownarrow . \\vert \\Vert \\\\|""".split()) _left_delim = set(r"( [ \{ < \lfloor \langle \lceil".split()) _right_delim = set(r") ] \} > \rfloor \rangle \rceil".split()) def __init__(self): p = Bunch() # All forward declarations are here p.accent = Forward() p.ambi_delim = Forward() p.apostrophe = Forward() p.auto_delim = Forward() p.binom = Forward() p.bslash = Forward() p.c_over_c = Forward() p.customspace = Forward() p.end_group = Forward() p.float_literal = Forward() p.font = Forward() p.frac = Forward() p.dfrac = Forward() p.function = Forward() p.genfrac = Forward() p.group = Forward() p.int_literal = Forward() p.latexfont = Forward() p.lbracket = Forward() p.left_delim = Forward() p.lbrace = Forward() p.main = Forward() p.math = Forward() p.math_string = Forward() p.non_math = Forward() p.operatorname = Forward() p.overline = Forward() p.placeable = Forward() p.rbrace = Forward() p.rbracket = Forward() p.required_group = Forward() p.right_delim = Forward() p.right_delim_safe = Forward() p.simple = Forward() p.simple_group = Forward() p.single_symbol = Forward() p.snowflake = Forward() p.space = Forward() p.sqrt = Forward() p.stackrel = Forward() p.start_group = Forward() p.subsuper = Forward() p.subsuperop = Forward() p.symbol = Forward() p.symbol_name = Forward() p.token = Forward() p.unknown_symbol = Forward() # Set names on everything -- very useful for debugging for key, val in vars(p).items(): if not key.startswith('_'): val.setName(key) p.float_literal <<= Regex(r"[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)") p.int_literal <<= Regex("[-+]?[0-9]+") p.lbrace <<= Literal('{').suppress() p.rbrace <<= Literal('}').suppress() p.lbracket <<= Literal('[').suppress() p.rbracket <<= Literal(']').suppress() p.bslash <<= Literal('\\') p.space <<= oneOf(list(self._space_widths)) p.customspace <<= (Suppress(Literal(r'\hspace')) - ((p.lbrace + p.float_literal + p.rbrace) | Error(r"Expected \hspace{n}"))) unicode_range = "\U00000080-\U0001ffff" p.single_symbol <<= Regex(r"([a-zA-Z0-9 +\-*/<>=:,.;!\?&'@()\[\]|%s])|(\\[%%${}\[\]_|])" % unicode_range) p.snowflake <<= Suppress(p.bslash) + oneOf(self._snowflake) p.symbol_name <<= (Combine(p.bslash + oneOf(list(tex2uni))) + FollowedBy(Regex("[^A-Za-z]").leaveWhitespace() | StringEnd())) p.symbol <<= (p.single_symbol | p.symbol_name).leaveWhitespace() p.apostrophe <<= Regex("'+") p.c_over_c <<= Suppress(p.bslash) + oneOf(list(self._char_over_chars)) p.accent <<= Group( Suppress(p.bslash) + oneOf(list(self._accent_map) + list(self._wide_accents)) - p.placeable ) p.function <<= Suppress(p.bslash) + oneOf(list(self._function_names)) p.start_group <<= Optional(p.latexfont) + p.lbrace p.end_group <<= p.rbrace.copy() p.simple_group <<= Group(p.lbrace + ZeroOrMore(p.token) + p.rbrace) p.required_group<<= Group(p.lbrace + OneOrMore(p.token) + p.rbrace) p.group <<= Group(p.start_group + ZeroOrMore(p.token) + p.end_group) p.font <<= Suppress(p.bslash) + oneOf(list(self._fontnames)) p.latexfont <<= Suppress(p.bslash) + oneOf(['math' + x for x in self._fontnames]) p.frac <<= Group( Suppress(Literal(r"\frac")) - ((p.required_group + p.required_group) | Error(r"Expected \frac{num}{den}")) ) p.dfrac <<= Group( Suppress(Literal(r"\dfrac")) - ((p.required_group + p.required_group) | Error(r"Expected \dfrac{num}{den}")) ) p.stackrel <<= Group( Suppress(Literal(r"\stackrel")) - ((p.required_group + p.required_group) | Error(r"Expected \stackrel{num}{den}")) ) p.binom <<= Group( Suppress(Literal(r"\binom")) - ((p.required_group + p.required_group) | Error(r"Expected \binom{num}{den}")) ) p.ambi_delim <<= oneOf(list(self._ambi_delim)) p.left_delim <<= oneOf(list(self._left_delim)) p.right_delim <<= oneOf(list(self._right_delim)) p.right_delim_safe <<= oneOf(list(self._right_delim - {'}'}) + [r'\}']) p.genfrac <<= Group( Suppress(Literal(r"\genfrac")) - (((p.lbrace + Optional(p.ambi_delim | p.left_delim, default='') + p.rbrace) + (p.lbrace + Optional(p.ambi_delim | p.right_delim_safe, default='') + p.rbrace) + (p.lbrace + p.float_literal + p.rbrace) + p.simple_group + p.required_group + p.required_group) | Error(r"Expected \genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}")) ) p.sqrt <<= Group( Suppress(Literal(r"\sqrt")) - ((Optional(p.lbracket + p.int_literal + p.rbracket, default=None) + p.required_group) | Error("Expected \\sqrt{value}")) ) p.overline <<= Group( Suppress(Literal(r"\overline")) - (p.required_group | Error("Expected \\overline{value}")) ) p.unknown_symbol<<= Combine(p.bslash + Regex("[A-Za-z]*")) p.operatorname <<= Group( Suppress(Literal(r"\operatorname")) - ((p.lbrace + ZeroOrMore(p.simple | p.unknown_symbol) + p.rbrace) | Error("Expected \\operatorname{value}")) ) p.placeable <<= ( p.snowflake # this needs to be before accent so named symbols # that are prefixed with an accent name work | p.accent # Must be before symbol as all accents are symbols | p.symbol # Must be third to catch all named symbols and single chars not in a group | p.c_over_c | p.function | p.group | p.frac | p.dfrac | p.stackrel | p.binom | p.genfrac | p.sqrt | p.overline | p.operatorname ) p.simple <<= ( p.space | p.customspace | p.font | p.subsuper ) p.subsuperop <<= oneOf(["_", "^"]) p.subsuper <<= Group( (Optional(p.placeable) + OneOrMore(p.subsuperop - p.placeable) + Optional(p.apostrophe)) | (p.placeable + Optional(p.apostrophe)) | p.apostrophe ) p.token <<= ( p.simple | p.auto_delim | p.unknown_symbol # Must be last ) p.auto_delim <<= (Suppress(Literal(r"\left")) - ((p.left_delim | p.ambi_delim) | Error("Expected a delimiter")) + Group(ZeroOrMore(p.simple | p.auto_delim)) + Suppress(Literal(r"\right")) - ((p.right_delim | p.ambi_delim) | Error("Expected a delimiter")) ) p.math <<= OneOrMore(p.token) p.math_string <<= QuotedString('$', '\\', unquoteResults=False) p.non_math <<= Regex(r"(?:(?:\\[$])|[^$])*").leaveWhitespace() p.main <<= (p.non_math + ZeroOrMore(p.math_string + p.non_math)) + StringEnd() # Set actions for key, val in vars(p).items(): if not key.startswith('_'): if hasattr(self, key): val.setParseAction(getattr(self, key)) self._expression = p.main self._math_expression = p.math def parse(self, s, fonts_object, fontsize, dpi): """ Parse expression *s* using the given *fonts_object* for output, at the given *fontsize* and *dpi*. Returns the parse tree of :class:`Node` instances. """ self._state_stack = [self.State(fonts_object, 'default', 'rm', fontsize, dpi)] self._em_width_cache = {} try: result = self._expression.parseString(s) except ParseBaseException as err: raise ValueError("\n".join([ "", err.line, " " * (err.column - 1) + "^", six.text_type(err)])) self._state_stack = None self._em_width_cache = {} self._expression.resetCache() return result[0] # The state of the parser is maintained in a stack. Upon # entering and leaving a group { } or math/non-math, the stack # is pushed and popped accordingly. The current state always # exists in the top element of the stack. class State(object): """ Stores the state of the parser. States are pushed and popped from a stack as necessary, and the "current" state is always at the top of the stack. """ def __init__(self, font_output, font, font_class, fontsize, dpi): self.font_output = font_output self._font = font self.font_class = font_class self.fontsize = fontsize self.dpi = dpi def copy(self): return Parser.State( self.font_output, self.font, self.font_class, self.fontsize, self.dpi) def _get_font(self): return self._font def _set_font(self, name): if name in ('rm', 'it', 'bf'): self.font_class = name self._font = name font = property(_get_font, _set_font) def get_state(self): """ Get the current :class:`State` of the parser. """ return self._state_stack[-1] def pop_state(self): """ Pop a :class:`State` off of the stack. """ self._state_stack.pop() def push_state(self): """ Push a new :class:`State` onto the stack which is just a copy of the current state. """ self._state_stack.append(self.get_state().copy()) def main(self, s, loc, toks): return [Hlist(toks)] def math_string(self, s, loc, toks): return self._math_expression.parseString(toks[0][1:-1]) def math(self, s, loc, toks): hlist = Hlist(toks) self.pop_state() return [hlist] def non_math(self, s, loc, toks): s = toks[0].replace(r'\$', '$') symbols = [Char(c, self.get_state(), math=False) for c in s] hlist = Hlist(symbols) # We're going into math now, so set font to 'it' self.push_state() self.get_state().font = rcParams['mathtext.default'] return [hlist] def _make_space(self, percentage): # All spaces are relative to em width state = self.get_state() key = (state.font, state.fontsize, state.dpi) width = self._em_width_cache.get(key) if width is None: metrics = state.font_output.get_metrics( state.font, rcParams['mathtext.default'], 'm', state.fontsize, state.dpi) width = metrics.advance self._em_width_cache[key] = width return Kern(width * percentage) _space_widths = { r'\,' : 0.16667, # 3/18 em = 3 mu r'\thinspace' : 0.16667, # 3/18 em = 3 mu r'\/' : 0.16667, # 3/18 em = 3 mu r'\>' : 0.22222, # 4/18 em = 4 mu r'\:' : 0.22222, # 4/18 em = 4 mu r'\;' : 0.27778, # 5/18 em = 5 mu r'\ ' : 0.33333, # 6/18 em = 6 mu r'\enspace' : 0.5, # 9/18 em = 9 mu r'\quad' : 1, # 1 em = 18 mu r'\qquad' : 2, # 2 em = 36 mu r'\!' : -0.16667, # -3/18 em = -3 mu } def space(self, s, loc, toks): assert len(toks)==1 num = self._space_widths[toks[0]] box = self._make_space(num) return [box] def customspace(self, s, loc, toks): return [self._make_space(float(toks[0]))] def symbol(self, s, loc, toks): c = toks[0] try: char = Char(c, self.get_state()) except ValueError: raise ParseFatalException(s, loc, "Unknown symbol: %s" % c) if c in self._spaced_symbols: # iterate until we find previous character, needed for cases # such as ${ -2}$, $ -2$, or $ -2$. for i in six.moves.xrange(1, loc + 1): prev_char = s[loc-i] if prev_char != ' ': break # Binary operators at start of string should not be spaced if (c in self._binary_operators and (len(s[:loc].split()) == 0 or prev_char == '{' or prev_char in self._left_delim)): return [char] else: return [Hlist([self._make_space(0.2), char, self._make_space(0.2)] , do_kern = True)] elif c in self._punctuation_symbols: # Do not space commas between brackets if c == ',': prev_char, next_char = '', '' for i in six.moves.xrange(1, loc + 1): prev_char = s[loc - i] if prev_char != ' ': break for i in six.moves.xrange(1, len(s) - loc): next_char = s[loc + i] if next_char != ' ': break if (prev_char == '{' and next_char == '}'): return [char] # Do not space dots as decimal separators if (c == '.' and s[loc - 1].isdigit() and s[loc + 1].isdigit()): return [char] else: return [Hlist([char, self._make_space(0.2)], do_kern = True)] return [char] snowflake = symbol def unknown_symbol(self, s, loc, toks): c = toks[0] raise ParseFatalException(s, loc, "Unknown symbol: %s" % c) _char_over_chars = { # The first 2 entries in the tuple are (font, char, sizescale) for # the two symbols under and over. The third element is the space # (in multiples of underline height) r'AA': (('it', 'A', 1.0), (None, '\\circ', 0.5), 0.0), } def c_over_c(self, s, loc, toks): sym = toks[0] state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) under_desc, over_desc, space = \ self._char_over_chars.get(sym, (None, None, 0.0)) if under_desc is None: raise ParseFatalException("Error parsing symbol") over_state = state.copy() if over_desc[0] is not None: over_state.font = over_desc[0] over_state.fontsize *= over_desc[2] over = Accent(over_desc[1], over_state) under_state = state.copy() if under_desc[0] is not None: under_state.font = under_desc[0] under_state.fontsize *= under_desc[2] under = Char(under_desc[1], under_state) width = max(over.width, under.width) over_centered = HCentered([over]) over_centered.hpack(width, 'exactly') under_centered = HCentered([under]) under_centered.hpack(width, 'exactly') return Vlist([ over_centered, Vbox(0., thickness * space), under_centered ]) _accent_map = { r'hat' : r'\circumflexaccent', r'breve' : r'\combiningbreve', r'bar' : r'\combiningoverline', r'grave' : r'\combininggraveaccent', r'acute' : r'\combiningacuteaccent', r'tilde' : r'\combiningtilde', r'dot' : r'\combiningdotabove', r'ddot' : r'\combiningdiaeresis', r'vec' : r'\combiningrightarrowabove', r'"' : r'\combiningdiaeresis', r"`" : r'\combininggraveaccent', r"'" : r'\combiningacuteaccent', r'~' : r'\combiningtilde', r'.' : r'\combiningdotabove', r'^' : r'\circumflexaccent', r'overrightarrow' : r'\rightarrow', r'overleftarrow' : r'\leftarrow', r'mathring' : r'\circ' } _wide_accents = set(r"widehat widetilde widebar".split()) # make a lambda and call it to get the namespace right _snowflake = (lambda am: [p for p in tex2uni if any(p.startswith(a) and a != p for a in am)] ) (set(_accent_map)) def accent(self, s, loc, toks): assert len(toks)==1 state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) if len(toks[0]) != 2: raise ParseFatalException("Error parsing accent") accent, sym = toks[0] if accent in self._wide_accents: accent_box = AutoWidthChar( '\\' + accent, sym.width, state, char_class=Accent) else: accent_box = Accent(self._accent_map[accent], state) if accent == 'mathring': accent_box.shrink() accent_box.shrink() centered = HCentered([Hbox(sym.width / 4.0), accent_box]) centered.hpack(sym.width, 'exactly') return Vlist([ centered, Vbox(0., thickness * 2.0), Hlist([sym]) ]) def function(self, s, loc, toks): self.push_state() state = self.get_state() state.font = 'rm' hlist = Hlist([Char(c, state) for c in toks[0]]) self.pop_state() hlist.function_name = toks[0] return hlist def operatorname(self, s, loc, toks): self.push_state() state = self.get_state() state.font = 'rm' # Change the font of Chars, but leave Kerns alone for c in toks[0]: if isinstance(c, Char): c.font = 'rm' c._update_metrics() self.pop_state() return Hlist(toks[0]) def start_group(self, s, loc, toks): self.push_state() # Deal with LaTeX-style font tokens if len(toks): self.get_state().font = toks[0][4:] return [] def group(self, s, loc, toks): grp = Hlist(toks[0]) return [grp] required_group = simple_group = group def end_group(self, s, loc, toks): self.pop_state() return [] def font(self, s, loc, toks): assert len(toks)==1 name = toks[0] self.get_state().font = name return [] def is_overunder(self, nucleus): if isinstance(nucleus, Char): return nucleus.c in self._overunder_symbols elif isinstance(nucleus, Hlist) and hasattr(nucleus, 'function_name'): return nucleus.function_name in self._overunder_functions return False def is_dropsub(self, nucleus): if isinstance(nucleus, Char): return nucleus.c in self._dropsub_symbols return False def is_slanted(self, nucleus): if isinstance(nucleus, Char): return nucleus.is_slanted() return False def is_between_brackets(self, s, loc): return False def subsuper(self, s, loc, toks): assert len(toks)==1 nucleus = None sub = None super = None # Pick all of the apostrophes out, including first apostrophes that have # been parsed as characters napostrophes = 0 new_toks = [] for tok in toks[0]: if isinstance(tok, six.string_types) and tok not in ('^', '_'): napostrophes += len(tok) elif isinstance(tok, Char) and tok.c == "'": napostrophes += 1 else: new_toks.append(tok) toks = new_toks if len(toks) == 0: assert napostrophes nucleus = Hbox(0.0) elif len(toks) == 1: if not napostrophes: return toks[0] # .asList() else: nucleus = toks[0] elif len(toks) in (2, 3): # single subscript or superscript nucleus = toks[0] if len(toks) == 3 else Hbox(0.0) op, next = toks[-2:] if op == '_': sub = next else: super = next elif len(toks) in (4, 5): # subscript and superscript nucleus = toks[0] if len(toks) == 5 else Hbox(0.0) op1, next1, op2, next2 = toks[-4:] if op1 == op2: if op1 == '_': raise ParseFatalException("Double subscript") else: raise ParseFatalException("Double superscript") if op1 == '_': sub = next1 super = next2 else: super = next1 sub = next2 else: raise ParseFatalException( "Subscript/superscript sequence is too long. " "Use braces { } to remove ambiguity.") state = self.get_state() rule_thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) xHeight = state.font_output.get_xheight( state.font, state.fontsize, state.dpi) if napostrophes: if super is None: super = Hlist([]) for i in range(napostrophes): super.children.extend(self.symbol(s, loc, ['\\prime'])) # kern() and hpack() needed to get the metrics right after extending super.kern() super.hpack() # Handle over/under symbols, such as sum or integral if self.is_overunder(nucleus): vlist = [] shift = 0. width = nucleus.width if super is not None: super.shrink() width = max(width, super.width) if sub is not None: sub.shrink() width = max(width, sub.width) if super is not None: hlist = HCentered([super]) hlist.hpack(width, 'exactly') vlist.extend([hlist, Kern(rule_thickness * 3.0)]) hlist = HCentered([nucleus]) hlist.hpack(width, 'exactly') vlist.append(hlist) if sub is not None: hlist = HCentered([sub]) hlist.hpack(width, 'exactly') vlist.extend([Kern(rule_thickness * 3.0), hlist]) shift = hlist.height vlist = Vlist(vlist) vlist.shift_amount = shift + nucleus.depth result = Hlist([vlist]) return [result] # We remove kerning on the last character for consistency (otherwise it # will compute kerning based on non-shrinked characters and may put them # too close together when superscripted) # We change the width of the last character to match the advance to # consider some fonts with weird metrics: e.g. stix's f has a width of # 7.75 and a kerning of -4.0 for an advance of 3.72, and we want to put # the superscript at the advance last_char = nucleus if isinstance(nucleus, Hlist): new_children = nucleus.children if len(new_children): # remove last kern if (isinstance(new_children[-1],Kern) and hasattr(new_children[-2], '_metrics')): new_children = new_children[:-1] last_char = new_children[-1] if hasattr(last_char, '_metrics'): last_char.width = last_char._metrics.advance # create new Hlist without kerning nucleus = Hlist(new_children, do_kern=False) else: if isinstance(nucleus, Char): last_char.width = last_char._metrics.advance nucleus = Hlist([nucleus]) # Handle regular sub/superscripts constants = _get_font_constant_set(state) lc_height = last_char.height lc_baseline = 0 if self.is_dropsub(last_char): lc_baseline = last_char.depth # Compute kerning for sub and super superkern = constants.delta * xHeight subkern = constants.delta * xHeight if self.is_slanted(last_char): superkern += constants.delta * xHeight superkern += (constants.delta_slanted * (lc_height - xHeight * 2. / 3.)) if self.is_dropsub(last_char): subkern = (3 * constants.delta - constants.delta_integral) * lc_height superkern = (3 * constants.delta + constants.delta_integral) * lc_height else: subkern = 0 if super is None: # node757 x = Hlist([Kern(subkern), sub]) x.shrink() if self.is_dropsub(last_char): shift_down = lc_baseline + constants.subdrop * xHeight else: shift_down = constants.sub1 * xHeight x.shift_amount = shift_down else: x = Hlist([Kern(superkern), super]) x.shrink() if self.is_dropsub(last_char): shift_up = lc_height - constants.subdrop * xHeight else: shift_up = constants.sup1 * xHeight if sub is None: x.shift_amount = -shift_up else: # Both sub and superscript y = Hlist([Kern(subkern),sub]) y.shrink() if self.is_dropsub(last_char): shift_down = lc_baseline + constants.subdrop * xHeight else: shift_down = constants.sub2 * xHeight # If sub and superscript collide, move super up clr = (2.0 * rule_thickness - ((shift_up - x.depth) - (y.height - shift_down))) if clr > 0.: shift_up += clr x = Vlist([x, Kern((shift_up - x.depth) - (y.height - shift_down)), y]) x.shift_amount = shift_down if not self.is_dropsub(last_char): x.width += constants.script_space * xHeight result = Hlist([nucleus, x]) return [result] def _genfrac(self, ldelim, rdelim, rule, style, num, den): state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) rule = float(rule) # If style != displaystyle == 0, shrink the num and den if style != self._math_style_dict['displaystyle']: num.shrink() den.shrink() cnum = HCentered([num]) cden = HCentered([den]) width = max(num.width, den.width) cnum.hpack(width, 'exactly') cden.hpack(width, 'exactly') vlist = Vlist([cnum, # numerator Vbox(0, thickness * 2.0), # space Hrule(state, rule), # rule Vbox(0, thickness * 2.0), # space cden # denominator ]) # Shift so the fraction line sits in the middle of the # equals sign metrics = state.font_output.get_metrics( state.font, rcParams['mathtext.default'], '=', state.fontsize, state.dpi) shift = (cden.height - ((metrics.ymax + metrics.ymin) / 2 - thickness * 3.0)) vlist.shift_amount = shift result = [Hlist([vlist, Hbox(thickness * 2.)])] if ldelim or rdelim: if ldelim == '': ldelim = '.' if rdelim == '': rdelim = '.' return self._auto_sized_delimiter(ldelim, result, rdelim) return result def genfrac(self, s, loc, toks): assert len(toks) == 1 assert len(toks[0]) == 6 return self._genfrac(*tuple(toks[0])) def frac(self, s, loc, toks): assert len(toks) == 1 assert len(toks[0]) == 2 state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) num, den = toks[0] return self._genfrac('', '', thickness, self._math_style_dict['textstyle'], num, den) def dfrac(self, s, loc, toks): assert len(toks) == 1 assert len(toks[0]) == 2 state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) num, den = toks[0] return self._genfrac('', '', thickness, self._math_style_dict['displaystyle'], num, den) def stackrel(self, s, loc, toks): assert len(toks) == 1 assert len(toks[0]) == 2 num, den = toks[0] return self._genfrac('', '', 0.0, self._math_style_dict['textstyle'], num, den) def binom(self, s, loc, toks): assert len(toks) == 1 assert len(toks[0]) == 2 num, den = toks[0] return self._genfrac('(', ')', 0.0, self._math_style_dict['textstyle'], num, den) def sqrt(self, s, loc, toks): root, body = toks[0] state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) # Determine the height of the body, and add a little extra to # the height so it doesn't seem cramped height = body.height - body.shift_amount + thickness * 5.0 depth = body.depth + body.shift_amount check = AutoHeightChar(r'\__sqrt__', height, depth, state, always=True) height = check.height - check.shift_amount depth = check.depth + check.shift_amount # Put a little extra space to the left and right of the body padded_body = Hlist([Hbox(thickness * 2.0), body, Hbox(thickness * 2.0)]) rightside = Vlist([Hrule(state), Fill(), padded_body]) # Stretch the glue between the hrule and the body rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), 'exactly', depth) # Add the root and shift it upward so it is above the tick. # The value of 0.6 is a hard-coded hack ;) if root is None: root = Box(check.width * 0.5, 0., 0.) else: root = Hlist([Char(x, state) for x in root]) root.shrink() root.shrink() root_vlist = Vlist([Hlist([root])]) root_vlist.shift_amount = -height * 0.6 hlist = Hlist([root_vlist, # Root # Negative kerning to put root over tick Kern(-check.width * 0.5), check, # Check rightside]) # Body return [hlist] def overline(self, s, loc, toks): assert len(toks)==1 assert len(toks[0])==1 body = toks[0][0] state = self.get_state() thickness = state.font_output.get_underline_thickness( state.font, state.fontsize, state.dpi) height = body.height - body.shift_amount + thickness * 3.0 depth = body.depth + body.shift_amount # Place overline above body rightside = Vlist([Hrule(state), Fill(), Hlist([body])]) # Stretch the glue between the hrule and the body rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0), 'exactly', depth) hlist = Hlist([rightside]) return [hlist] def _auto_sized_delimiter(self, front, middle, back): state = self.get_state() if len(middle): height = max(x.height for x in middle) depth = max(x.depth for x in middle) factor = None else: height = 0 depth = 0 factor = 1.0 parts = [] # \left. and \right. aren't supposed to produce any symbols if front != '.': parts.append(AutoHeightChar(front, height, depth, state, factor=factor)) parts.extend(middle) if back != '.': parts.append(AutoHeightChar(back, height, depth, state, factor=factor)) hlist = Hlist(parts) return hlist def auto_delim(self, s, loc, toks): front, middle, back = toks return self._auto_sized_delimiter(front, middle.asList(), back) ### ############################################################################## # MAIN class MathTextParser(object): _parser = None _backend_mapping = { 'bitmap': MathtextBackendBitmap, 'agg' : MathtextBackendAgg, 'ps' : MathtextBackendPs, 'pdf' : MathtextBackendPdf, 'svg' : MathtextBackendSvg, 'path' : MathtextBackendPath, 'cairo' : MathtextBackendCairo, 'macosx': MathtextBackendAgg, } _font_type_mapping = { 'cm' : BakomaFonts, 'dejavuserif' : DejaVuSerifFonts, 'dejavusans' : DejaVuSansFonts, 'stix' : StixFonts, 'stixsans' : StixSansFonts, 'custom' : UnicodeFonts } def __init__(self, output): """ Create a MathTextParser for the given backend *output*. """ self._output = output.lower() self._cache = maxdict(50) def parse(self, s, dpi = 72, prop = None): """ Parse the given math expression *s* at the given *dpi*. If *prop* is provided, it is a :class:`~matplotlib.font_manager.FontProperties` object specifying the "default" font to use in the math expression, used for all non-math text. The results are cached, so multiple calls to :meth:`parse` with the same expression should be fast. """ # There is a bug in Python 3.x where it leaks frame references, # and therefore can't handle this caching if prop is None: prop = FontProperties() cacheKey = (s, dpi, hash(prop)) result = self._cache.get(cacheKey) if result is not None: return result if self._output == 'ps' and rcParams['ps.useafm']: font_output = StandardPsFonts(prop) else: backend = self._backend_mapping[self._output]() fontset = rcParams['mathtext.fontset'] fontset_class = self._font_type_mapping.get(fontset.lower()) if fontset_class is not None: font_output = fontset_class(prop, backend) else: raise ValueError( "mathtext.fontset must be either 'cm', 'dejavuserif', " "'dejavusans', 'stix', 'stixsans', or 'custom'") fontsize = prop.get_size_in_points() # This is a class variable so we don't rebuild the parser # with each request. if self._parser is None: self.__class__._parser = Parser() box = self._parser.parse(s, font_output, fontsize, dpi) font_output.set_canvas_size(box.width, box.height, box.depth) result = font_output.get_results(box) self._cache[cacheKey] = result return result def to_mask(self, texstr, dpi=120, fontsize=14): """ *texstr* A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$' *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline from the bottom of the image in pixels. """ assert self._output == "bitmap" prop = FontProperties(size=fontsize) ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop) x = ftimage.as_array() return x, depth def to_rgba(self, texstr, color='black', dpi=120, fontsize=14): """ *texstr* A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$' *color* Any matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns a tuple (*array*, *depth*) - *array* is an NxM uint8 alpha ubyte mask array of rasterized tex. - depth is the offset of the baseline from the bottom of the image in pixels. """ x, depth = self.to_mask(texstr, dpi=dpi, fontsize=fontsize) r, g, b, a = mcolors.to_rgba(color) RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8) RGBA[:, :, 0] = 255 * r RGBA[:, :, 1] = 255 * g RGBA[:, :, 2] = 255 * b RGBA[:, :, 3] = x return RGBA, depth def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14): """ Writes a tex expression to a PNG file. Returns the offset of the baseline from the bottom of the image in pixels. *filename* A writable filename or fileobject *texstr* A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$' *color* A valid matplotlib color argument *dpi* The dots-per-inch to render the text *fontsize* The font size in points Returns the offset of the baseline from the bottom of the image in pixels. """ rgba, depth = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize) _png.write_png(rgba, filename) return depth def get_depth(self, texstr, dpi=120, fontsize=14): """ Returns the offset of the baseline from the bottom of the image in pixels. *texstr* A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$' *dpi* The dots-per-inch to render the text *fontsize* The font size in points """ assert self._output=="bitmap" prop = FontProperties(size=fontsize) ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop) return depth def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None): """ Given a math expression, renders it in a closely-clipped bounding box to an image file. *s* A math expression. The math portion should be enclosed in dollar signs. *filename_or_obj* A filepath or writable file-like object to write the image data to. *prop* If provided, a FontProperties() object describing the size and style of the text. *dpi* Override the output dpi, otherwise use the default associated with the output format. *format* The output format, e.g., 'svg', 'pdf', 'ps' or 'png'. If not provided, will be deduced from the filename. """ from matplotlib import figure # backend_agg supports all of the core output formats from matplotlib.backends import backend_agg if prop is None: prop = FontProperties() parser = MathTextParser('path') width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop) fig = figure.Figure(figsize=(width / 72.0, height / 72.0)) fig.text(0, depth/height, s, fontproperties=prop) backend_agg.FigureCanvasAgg(fig) fig.savefig(filename_or_obj, dpi=dpi, format=format) return depth
122,489
34.54556
117
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/patches.py
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import map, zip import math import warnings import numpy as np import matplotlib as mpl from . import artist, cbook, colors, docstring, lines as mlines, transforms from .bezier import ( concatenate_paths, get_cos_sin, get_intersection, get_parallels, inside_circle, make_path_regular, make_wedged_bezier2, split_bezier_intersecting_with_closedpath, split_path_inout) from .path import Path _patch_alias_map = { 'antialiased': ['aa'], 'edgecolor': ['ec'], 'facecolor': ['fc'], 'linewidth': ['lw'], 'linestyle': ['ls'] } class Patch(artist.Artist): """ A patch is a 2D artist with a face color and an edge color. If any of *edgecolor*, *facecolor*, *linewidth*, or *antialiased* are *None*, they default to their rc params setting. """ zorder = 1 validCap = ('butt', 'round', 'projecting') validJoin = ('miter', 'round', 'bevel') # Whether to draw an edge by default. Set on a # subclass-by-subclass basis. _edge_default = False def __str__(self): return str(self.__class__).split('.')[-1] def __init__(self, edgecolor=None, facecolor=None, color=None, linewidth=None, linestyle=None, antialiased=None, hatch=None, fill=True, capstyle=None, joinstyle=None, **kwargs): """ The following kwarg properties are supported %(Patch)s """ artist.Artist.__init__(self) if linewidth is None: linewidth = mpl.rcParams['patch.linewidth'] if linestyle is None: linestyle = "solid" if capstyle is None: capstyle = 'butt' if joinstyle is None: joinstyle = 'miter' if antialiased is None: antialiased = mpl.rcParams['patch.antialiased'] self._hatch_color = colors.to_rgba(mpl.rcParams['hatch.color']) self._fill = True # needed for set_facecolor call if color is not None: if (edgecolor is not None or facecolor is not None): warnings.warn("Setting the 'color' property will override" "the edgecolor or facecolor properties. ") self.set_color(color) else: self.set_edgecolor(edgecolor) self.set_facecolor(facecolor) # unscaled dashes. Needed to scale dash patterns by lw self._us_dashes = None self._linewidth = 0 self.set_fill(fill) self.set_linestyle(linestyle) self.set_linewidth(linewidth) self.set_antialiased(antialiased) self.set_hatch(hatch) self.set_capstyle(capstyle) self.set_joinstyle(joinstyle) self._combined_transform = transforms.IdentityTransform() if len(kwargs): self.update(kwargs) def get_verts(self): """ Return a copy of the vertices used in this patch If the patch contains Bezier curves, the curves will be interpolated by line segments. To access the curves as curves, use :meth:`get_path`. """ trans = self.get_transform() path = self.get_path() polygons = path.to_polygons(trans) if len(polygons): return polygons[0] return [] def _process_radius(self, radius): if radius is not None: return radius if cbook.is_numlike(self._picker): _radius = self._picker else: if self.get_edgecolor()[3] == 0: _radius = 0 else: _radius = self.get_linewidth() return _radius def contains(self, mouseevent, radius=None): """Test whether the mouse event occurred in the patch. Returns T/F, {} """ if callable(self._contains): return self._contains(self, mouseevent) radius = self._process_radius(radius) inside = self.get_path().contains_point( (mouseevent.x, mouseevent.y), self.get_transform(), radius) return inside, {} def contains_point(self, point, radius=None): """ Returns ``True`` if the given *point* is inside the path (transformed with its transform attribute). *radius* allows the path to be made slightly larger or smaller. """ radius = self._process_radius(radius) return self.get_path().contains_point(point, self.get_transform(), radius) def contains_points(self, points, radius=None): """ Returns a bool array which is ``True`` if the (closed) path contains the corresponding point. (transformed with its transform attribute). *points* must be Nx2 array. *radius* allows the path to be made slightly larger or smaller. """ radius = self._process_radius(radius) return self.get_path().contains_points(points, self.get_transform(), radius) def update_from(self, other): """ Updates this :class:`Patch` from the properties of *other*. """ artist.Artist.update_from(self, other) # For some properties we don't need or don't want to go through the # getters/setters, so we just copy them directly. self._edgecolor = other._edgecolor self._facecolor = other._facecolor self._fill = other._fill self._hatch = other._hatch self._hatch_color = other._hatch_color # copy the unscaled dash pattern self._us_dashes = other._us_dashes self.set_linewidth(other._linewidth) # also sets dash properties self.set_transform(other.get_data_transform()) def get_extents(self): """ Return a :class:`~matplotlib.transforms.Bbox` object defining the axis-aligned extents of the :class:`Patch`. """ return self.get_path().get_extents(self.get_transform()) def get_transform(self): """ Return the :class:`~matplotlib.transforms.Transform` applied to the :class:`Patch`. """ return self.get_patch_transform() + artist.Artist.get_transform(self) def get_data_transform(self): """ Return the :class:`~matplotlib.transforms.Transform` instance which maps data coordinates to physical coordinates. """ return artist.Artist.get_transform(self) def get_patch_transform(self): """ Return the :class:`~matplotlib.transforms.Transform` instance which takes patch coordinates to data coordinates. For example, one may define a patch of a circle which represents a radius of 5 by providing coordinates for a unit circle, and a transform which scales the coordinates (the patch coordinate) by 5. """ return transforms.IdentityTransform() def get_antialiased(self): """ Returns True if the :class:`Patch` is to be drawn with antialiasing. """ return self._antialiased get_aa = get_antialiased def get_edgecolor(self): """ Return the edge color of the :class:`Patch`. """ return self._edgecolor get_ec = get_edgecolor def get_facecolor(self): """ Return the face color of the :class:`Patch`. """ return self._facecolor get_fc = get_facecolor def get_linewidth(self): """ Return the line width in points. """ return self._linewidth get_lw = get_linewidth def get_linestyle(self): """ Return the linestyle. Will be one of ['solid' | 'dashed' | 'dashdot' | 'dotted'] """ return self._linestyle get_ls = get_linestyle def set_antialiased(self, aa): """ Set whether to use antialiased rendering. Parameters ---------- b : bool or None .. ACCEPTS: bool or None """ if aa is None: aa = mpl.rcParams['patch.antialiased'] self._antialiased = aa self.stale = True def set_aa(self, aa): """alias for set_antialiased""" return self.set_antialiased(aa) def _set_edgecolor(self, color): set_hatch_color = True if color is None: if (mpl.rcParams['patch.force_edgecolor'] or not self._fill or self._edge_default): color = mpl.rcParams['patch.edgecolor'] else: color = 'none' set_hatch_color = False self._edgecolor = colors.to_rgba(color, self._alpha) if set_hatch_color: self._hatch_color = self._edgecolor self.stale = True def set_edgecolor(self, color): """ Set the patch edge color ACCEPTS: mpl color spec, None, 'none', or 'auto' """ self._original_edgecolor = color self._set_edgecolor(color) def set_ec(self, color): """alias for set_edgecolor""" return self.set_edgecolor(color) def _set_facecolor(self, color): if color is None: color = mpl.rcParams['patch.facecolor'] alpha = self._alpha if self._fill else 0 self._facecolor = colors.to_rgba(color, alpha) self.stale = True def set_facecolor(self, color): """ Set the patch face color ACCEPTS: mpl color spec, or None for default, or 'none' for no color """ self._original_facecolor = color self._set_facecolor(color) def set_fc(self, color): """alias for set_facecolor""" return self.set_facecolor(color) def set_color(self, c): """ Set both the edgecolor and the facecolor. ACCEPTS: matplotlib color spec .. seealso:: :meth:`set_facecolor`, :meth:`set_edgecolor` For setting the edge or face color individually. """ self.set_facecolor(c) self.set_edgecolor(c) def set_alpha(self, alpha): """ Set the alpha tranparency of the patch. ACCEPTS: float or None """ if alpha is not None: try: float(alpha) except TypeError: raise TypeError('alpha must be a float or None') artist.Artist.set_alpha(self, alpha) self._set_facecolor(self._original_facecolor) self._set_edgecolor(self._original_edgecolor) # stale is already True def set_linewidth(self, w): """ Set the patch linewidth in points ACCEPTS: float or None for default """ if w is None: w = mpl.rcParams['patch.linewidth'] if w is None: w = mpl.rcParams['axes.linewidth'] self._linewidth = float(w) # scale the dash pattern by the linewidth offset, ls = self._us_dashes self._dashoffset, self._dashes = mlines._scale_dashes( offset, ls, self._linewidth) self.stale = True def set_lw(self, lw): """alias for set_linewidth""" return self.set_linewidth(lw) def set_linestyle(self, ls): """ Set the patch linestyle =========================== ================= linestyle description =========================== ================= ``'-'`` or ``'solid'`` solid line ``'--'`` or ``'dashed'`` dashed line ``'-.'`` or ``'dashdot'`` dash-dotted line ``':'`` or ``'dotted'`` dotted line =========================== ================= Alternatively a dash tuple of the following form can be provided:: (offset, onoffseq), where ``onoffseq`` is an even length tuple of on and off ink in points. ACCEPTS: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``] Parameters ---------- ls : { '-', '--', '-.', ':'} and more see description The line style. """ if ls is None: ls = "solid" self._linestyle = ls # get the unscalled dash pattern offset, ls = self._us_dashes = mlines._get_dash_pattern(ls) # scale the dash pattern by the linewidth self._dashoffset, self._dashes = mlines._scale_dashes( offset, ls, self._linewidth) self.stale = True def set_ls(self, ls): """alias for set_linestyle""" return self.set_linestyle(ls) def set_fill(self, b): """ Set whether to fill the patch. Parameters ---------- b : bool .. ACCEPTS: bool """ self._fill = bool(b) self._set_facecolor(self._original_facecolor) self._set_edgecolor(self._original_edgecolor) self.stale = True def get_fill(self): 'return whether fill is set' return self._fill # Make fill a property so as to preserve the long-standing # but somewhat inconsistent behavior in which fill was an # attribute. fill = property(get_fill, set_fill) def set_capstyle(self, s): """ Set the patch capstyle ACCEPTS: ['butt' | 'round' | 'projecting'] """ s = s.lower() if s not in self.validCap: raise ValueError('set_capstyle passed "%s";\n' % (s,) + 'valid capstyles are %s' % (self.validCap,)) self._capstyle = s self.stale = True def get_capstyle(self): "Return the current capstyle" return self._capstyle def set_joinstyle(self, s): """ Set the patch joinstyle ACCEPTS: ['miter' | 'round' | 'bevel'] """ s = s.lower() if s not in self.validJoin: raise ValueError('set_joinstyle passed "%s";\n' % (s,) + 'valid joinstyles are %s' % (self.validJoin,)) self._joinstyle = s self.stale = True def get_joinstyle(self): "Return the current joinstyle" return self._joinstyle def set_hatch(self, hatch): """ Set the hatching pattern *hatch* can be one of:: / - diagonal hatching \\ - back diagonal | - vertical - - horizontal + - crossed x - crossed diagonal o - small circle O - large circle . - dots * - stars Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. ACCEPTS: ['/' | '\\\\' | '|' | '-' | '+' | 'x' | 'o' | 'O' | '.' | '*'] """ self._hatch = hatch self.stale = True def get_hatch(self): 'Return the current hatching pattern' return self._hatch @artist.allow_rasterization def draw(self, renderer): 'Draw the :class:`Patch` to the given *renderer*.' if not self.get_visible(): return renderer.open_group('patch', self.get_gid()) gc = renderer.new_gc() gc.set_foreground(self._edgecolor, isRGBA=True) lw = self._linewidth if self._edgecolor[3] == 0: lw = 0 gc.set_linewidth(lw) gc.set_dashes(0, self._dashes) gc.set_capstyle(self._capstyle) gc.set_joinstyle(self._joinstyle) gc.set_antialiased(self._antialiased) self._set_gc_clip(gc) gc.set_url(self._url) gc.set_snap(self.get_snap()) rgbFace = self._facecolor if rgbFace[3] == 0: rgbFace = None # (some?) renderers expect this as no-fill signal gc.set_alpha(self._alpha) if self._hatch: gc.set_hatch(self._hatch) try: gc.set_hatch_color(self._hatch_color) except AttributeError: # if we end up with a GC that does not have this method warnings.warn("Your backend does not have support for " "setting the hatch color.") if self.get_sketch_params() is not None: gc.set_sketch_params(*self.get_sketch_params()) path = self.get_path() transform = self.get_transform() tpath = transform.transform_path_non_affine(path) affine = transform.get_affine() if self.get_path_effects(): from matplotlib.patheffects import PathEffectRenderer renderer = PathEffectRenderer(self.get_path_effects(), renderer) renderer.draw_path(gc, tpath, affine, rgbFace) gc.restore() renderer.close_group('patch') self.stale = False def get_path(self): """ Return the path of this patch """ raise NotImplementedError('Derived must override') def get_window_extent(self, renderer=None): return self.get_path().get_extents(self.get_transform()) patchdoc = artist.kwdoc(Patch) for k in ('Rectangle', 'Circle', 'RegularPolygon', 'Polygon', 'Wedge', 'Arrow', 'FancyArrow', 'YAArrow', 'CirclePolygon', 'Ellipse', 'Arc', 'FancyBboxPatch', 'Patch'): docstring.interpd.update({k: patchdoc}) # define Patch.__init__ docstring after the class has been added to interpd docstring.dedent_interpd(Patch.__init__) class Shadow(Patch): def __str__(self): return "Shadow(%s)" % (str(self.patch)) @docstring.dedent_interpd def __init__(self, patch, ox, oy, props=None, **kwargs): """ Create a shadow of the given *patch* offset by *ox*, *oy*. *props*, if not *None*, is a patch property update dictionary. If *None*, the shadow will have have the same color as the face, but darkened. kwargs are %(Patch)s """ Patch.__init__(self) self.patch = patch self.props = props self._ox, self._oy = ox, oy self._shadow_transform = transforms.Affine2D() self._update() def _update(self): self.update_from(self.patch) # Place the shadow patch directly behind the inherited patch. self.set_zorder(np.nextafter(self.patch.zorder, -np.inf)) if self.props is not None: self.update(self.props) else: r, g, b, a = colors.to_rgba(self.patch.get_facecolor()) rho = 0.3 r = rho * r g = rho * g b = rho * b self.set_facecolor((r, g, b, 0.5)) self.set_edgecolor((r, g, b, 0.5)) self.set_alpha(0.5) def _update_transform(self, renderer): ox = renderer.points_to_pixels(self._ox) oy = renderer.points_to_pixels(self._oy) self._shadow_transform.clear().translate(ox, oy) def _get_ox(self): return self._ox def _set_ox(self, ox): self._ox = ox def _get_oy(self): return self._oy def _set_oy(self, oy): self._oy = oy def get_path(self): return self.patch.get_path() def get_patch_transform(self): return self.patch.get_patch_transform() + self._shadow_transform def draw(self, renderer): self._update_transform(renderer) Patch.draw(self, renderer) class Rectangle(Patch): """ Draw a rectangle with lower left at *xy* = (*x*, *y*) with specified *width*, *height* and rotation *angle*. """ def __str__(self): pars = self._x0, self._y0, self._width, self._height, self.angle fmt = "Rectangle(xy=(%g, %g), width=%g, height=%g, angle=%g)" return fmt % pars @docstring.dedent_interpd def __init__(self, xy, width, height, angle=0.0, **kwargs): """ Parameters ---------- xy: length-2 tuple The bottom and left rectangle coordinates width: Rectangle width height: Rectangle height angle: float, optional rotation in degrees anti-clockwise about *xy* (default is 0.0) fill: bool, optional Whether to fill the rectangle (default is ``True``) Notes ----- Valid kwargs are: %(Patch)s """ Patch.__init__(self, **kwargs) self._x0 = xy[0] self._y0 = xy[1] self._width = width self._height = height self._x1 = self._x0 + self._width self._y1 = self._y0 + self._height self.angle = float(angle) # Note: This cannot be calculated until this is added to an Axes self._rect_transform = transforms.IdentityTransform() def get_path(self): """ Return the vertices of the rectangle """ return Path.unit_rectangle() def _update_patch_transform(self): """NOTE: This cannot be called until after this has been added to an Axes, otherwise unit conversion will fail. This makes it very important to call the accessor method and not directly access the transformation member variable. """ x0, y0, x1, y1 = self._convert_units() bbox = transforms.Bbox.from_extents(x0, y0, x1, y1) rot_trans = transforms.Affine2D() rot_trans.rotate_deg_around(x0, y0, self.angle) self._rect_transform = transforms.BboxTransformTo(bbox) self._rect_transform += rot_trans def _update_x1(self): self._x1 = self._x0 + self._width def _update_y1(self): self._y1 = self._y0 + self._height def _convert_units(self): ''' Convert bounds of the rectangle ''' x0 = self.convert_xunits(self._x0) y0 = self.convert_yunits(self._y0) x1 = self.convert_xunits(self._x1) y1 = self.convert_yunits(self._y1) return x0, y0, x1, y1 def get_patch_transform(self): self._update_patch_transform() return self._rect_transform def get_x(self): "Return the left coord of the rectangle" return self._x0 def get_y(self): "Return the bottom coord of the rectangle" return self._y0 def get_xy(self): "Return the left and bottom coords of the rectangle" return self._x0, self._y0 def get_width(self): "Return the width of the rectangle" return self._width def get_height(self): "Return the height of the rectangle" return self._height def set_x(self, x): "Set the left coord of the rectangle" self._x0 = x self._update_x1() self.stale = True def set_y(self, y): "Set the bottom coord of the rectangle" self._y0 = y self._update_y1() self.stale = True def set_xy(self, xy): """ Set the left and bottom coords of the rectangle ACCEPTS: 2-item sequence """ self._x0, self._y0 = xy self._update_x1() self._update_y1() self.stale = True def set_width(self, w): "Set the width of the rectangle" self._width = w self._update_x1() self.stale = True def set_height(self, h): "Set the height of the rectangle" self._height = h self._update_y1() self.stale = True def set_bounds(self, *args): """ Set the bounds of the rectangle: l,b,w,h ACCEPTS: (left, bottom, width, height) """ if len(args) == 0: l, b, w, h = args[0] else: l, b, w, h = args self._x0 = l self._y0 = b self._width = w self._height = h self._update_x1() self._update_y1() self.stale = True def get_bbox(self): x0, y0, x1, y1 = self._convert_units() return transforms.Bbox.from_extents(x0, y0, x1, y1) xy = property(get_xy, set_xy) class RegularPolygon(Patch): """ A regular polygon patch. """ def __str__(self): return "Poly%d(%g,%g)" % (self._numVertices, self._xy[0], self._xy[1]) @docstring.dedent_interpd def __init__(self, xy, numVertices, radius=5, orientation=0, **kwargs): """ Constructor arguments: *xy* A length 2 tuple (*x*, *y*) of the center. *numVertices* the number of vertices. *radius* The distance from the center to each of the vertices. *orientation* rotates the polygon (in radians). Valid kwargs are: %(Patch)s """ self._xy = xy self._numVertices = numVertices self._orientation = orientation self._radius = radius self._path = Path.unit_regular_polygon(numVertices) self._poly_transform = transforms.Affine2D() self._update_transform() Patch.__init__(self, **kwargs) def _update_transform(self): self._poly_transform.clear() \ .scale(self.radius) \ .rotate(self.orientation) \ .translate(*self.xy) def _get_xy(self): return self._xy def _set_xy(self, xy): self._xy = xy self._update_transform() xy = property(_get_xy, _set_xy) def _get_orientation(self): return self._orientation def _set_orientation(self, orientation): self._orientation = orientation self._update_transform() orientation = property(_get_orientation, _set_orientation) def _get_radius(self): return self._radius def _set_radius(self, radius): self._radius = radius self._update_transform() radius = property(_get_radius, _set_radius) def _get_numvertices(self): return self._numVertices def _set_numvertices(self, numVertices): self._numVertices = numVertices numvertices = property(_get_numvertices, _set_numvertices) def get_path(self): return self._path def get_patch_transform(self): self._update_transform() return self._poly_transform class PathPatch(Patch): """ A general polycurve path patch. """ _edge_default = True def __str__(self): return "Poly((%g, %g) ...)" % tuple(self._path.vertices[0]) @docstring.dedent_interpd def __init__(self, path, **kwargs): """ *path* is a :class:`matplotlib.path.Path` object. Valid kwargs are: %(Patch)s .. seealso:: :class:`Patch` For additional kwargs """ Patch.__init__(self, **kwargs) self._path = path def get_path(self): return self._path class Polygon(Patch): """ A general polygon patch. """ def __str__(self): return "Poly((%g, %g) ...)" % tuple(self._path.vertices[0]) @docstring.dedent_interpd def __init__(self, xy, closed=True, **kwargs): """ *xy* is a numpy array with shape Nx2. If *closed* is *True*, the polygon will be closed so the starting and ending points are the same. Valid kwargs are: %(Patch)s .. seealso:: :class:`Patch` For additional kwargs """ Patch.__init__(self, **kwargs) self._closed = closed self.set_xy(xy) def get_path(self): """ Get the path of the polygon Returns ------- path : Path The :class:`~matplotlib.path.Path` object for the polygon """ return self._path def get_closed(self): """ Returns if the polygon is closed Returns ------- closed : bool If the path is closed """ return self._closed def set_closed(self, closed): """ Set if the polygon is closed Parameters ---------- closed : bool True if the polygon is closed """ if self._closed == bool(closed): return self._closed = bool(closed) self.set_xy(self.get_xy()) self.stale = True def get_xy(self): """ Get the vertices of the path Returns ------- vertices : numpy array The coordinates of the vertices as a Nx2 ndarray. """ return self._path.vertices def set_xy(self, xy): """ Set the vertices of the polygon Parameters ---------- xy : numpy array or iterable of pairs The coordinates of the vertices as a Nx2 ndarray or iterable of pairs. """ xy = np.asarray(xy) if self._closed: if len(xy) and (xy[0] != xy[-1]).any(): xy = np.concatenate([xy, [xy[0]]]) else: if len(xy) > 2 and (xy[0] == xy[-1]).all(): xy = xy[:-1] self._path = Path(xy, closed=self._closed) self.stale = True _get_xy = get_xy _set_xy = set_xy xy = property( get_xy, set_xy, None, """Set/get the vertices of the polygon. This property is provided for backward compatibility with matplotlib 0.91.x only. New code should use :meth:`~matplotlib.patches.Polygon.get_xy` and :meth:`~matplotlib.patches.Polygon.set_xy` instead.""") class Wedge(Patch): """ Wedge shaped patch. """ def __str__(self): pars = (self.center[0], self.center[1], self.r, self.theta1, self.theta2, self.width) fmt = "Wedge(center=(%g, %g), r=%g, theta1=%g, theta2=%g, width=%s)" return fmt % pars @docstring.dedent_interpd def __init__(self, center, r, theta1, theta2, width=None, **kwargs): """ Draw a wedge centered at *x*, *y* center with radius *r* that sweeps *theta1* to *theta2* (in degrees). If *width* is given, then a partial wedge is drawn from inner radius *r* - *width* to outer radius *r*. Valid kwargs are: %(Patch)s """ Patch.__init__(self, **kwargs) self.center = center self.r, self.width = r, width self.theta1, self.theta2 = theta1, theta2 self._patch_transform = transforms.IdentityTransform() self._recompute_path() def _recompute_path(self): # Inner and outer rings are connected unless the annulus is complete if abs((self.theta2 - self.theta1) - 360) <= 1e-12: theta1, theta2 = 0, 360 connector = Path.MOVETO else: theta1, theta2 = self.theta1, self.theta2 connector = Path.LINETO # Form the outer ring arc = Path.arc(theta1, theta2) if self.width is not None: # Partial annulus needs to draw the outer ring # followed by a reversed and scaled inner ring v1 = arc.vertices v2 = arc.vertices[::-1] * (self.r - self.width) / self.r v = np.vstack([v1, v2, v1[0, :], (0, 0)]) c = np.hstack([arc.codes, arc.codes, connector, Path.CLOSEPOLY]) c[len(arc.codes)] = connector else: # Wedge doesn't need an inner ring v = np.vstack([arc.vertices, [(0, 0), arc.vertices[0, :], (0, 0)]]) c = np.hstack([arc.codes, [connector, connector, Path.CLOSEPOLY]]) # Shift and scale the wedge to the final location. v *= self.r v += np.asarray(self.center) self._path = Path(v, c) def set_center(self, center): self._path = None self.center = center self.stale = True def set_radius(self, radius): self._path = None self.r = radius self.stale = True def set_theta1(self, theta1): self._path = None self.theta1 = theta1 self.stale = True def set_theta2(self, theta2): self._path = None self.theta2 = theta2 self.stale = True def set_width(self, width): self._path = None self.width = width self.stale = True def get_path(self): if self._path is None: self._recompute_path() return self._path # COVERAGE NOTE: Not used internally or from examples class Arrow(Patch): """ An arrow patch. """ def __str__(self): return "Arrow()" _path = Path([[0.0, 0.1], [0.0, -0.1], [0.8, -0.1], [0.8, -0.3], [1.0, 0.0], [0.8, 0.3], [0.8, 0.1], [0.0, 0.1]], closed=True) @docstring.dedent_interpd def __init__(self, x, y, dx, dy, width=1.0, **kwargs): """ Draws an arrow from (*x*, *y*) to (*x* + *dx*, *y* + *dy*). The width of the arrow is scaled by *width*. Parameters ---------- x : scalar x coordinate of the arrow tail y : scalar y coordinate of the arrow tail dx : scalar Arrow length in the x direction dy : scalar Arrow length in the y direction width : scalar, optional (default: 1) Scale factor for the width of the arrow. With a default value of 1, the tail width is 0.2 and head width is 0.6. **kwargs : Keyword arguments control the :class:`~matplotlib.patches.Patch` properties: %(Patch)s See Also -------- :class:`FancyArrow` : Patch that allows independent control of the head and tail properties """ Patch.__init__(self, **kwargs) L = np.hypot(dx, dy) if L != 0: cx = dx / L sx = dy / L else: # Account for division by zero cx, sx = 0, 1 trans1 = transforms.Affine2D().scale(L, width) trans2 = transforms.Affine2D.from_values(cx, sx, -sx, cx, 0.0, 0.0) trans3 = transforms.Affine2D().translate(x, y) trans = trans1 + trans2 + trans3 self._patch_transform = trans.frozen() def get_path(self): return self._path def get_patch_transform(self): return self._patch_transform class FancyArrow(Polygon): """ Like Arrow, but lets you set head width and head height independently. """ _edge_default = True def __str__(self): return "FancyArrow()" @docstring.dedent_interpd def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False, head_width=None, head_length=None, shape='full', overhang=0, head_starts_at_zero=False, **kwargs): """ Constructor arguments *width*: float (default: 0.001) width of full arrow tail *length_includes_head*: bool (default: False) True if head is to be counted in calculating the length. *head_width*: float or None (default: 3*width) total width of the full arrow head *head_length*: float or None (default: 1.5 * head_width) length of arrow head *shape*: ['full', 'left', 'right'] (default: 'full') draw the left-half, right-half, or full arrow *overhang*: float (default: 0) fraction that the arrow is swept back (0 overhang means triangular shape). Can be negative or greater than one. *head_starts_at_zero*: bool (default: False) if True, the head starts being drawn at coordinate 0 instead of ending at coordinate 0. Other valid kwargs (inherited from :class:`Patch`) are: %(Patch)s """ if head_width is None: head_width = 3 * width if head_length is None: head_length = 1.5 * head_width distance = np.hypot(dx, dy) if length_includes_head: length = distance else: length = distance + head_length if not length: verts = [] # display nothing if empty else: # start by drawing horizontal arrow, point at (0,0) hw, hl, hs, lw = head_width, head_length, overhang, width left_half_arrow = np.array([ [0.0, 0.0], # tip [-hl, -hw / 2.0], # leftmost [-hl * (1 - hs), -lw / 2.0], # meets stem [-length, -lw / 2.0], # bottom left [-length, 0], ]) # if we're not including the head, shift up by head length if not length_includes_head: left_half_arrow += [head_length, 0] # if the head starts at 0, shift up by another head length if head_starts_at_zero: left_half_arrow += [head_length / 2.0, 0] # figure out the shape, and complete accordingly if shape == 'left': coords = left_half_arrow else: right_half_arrow = left_half_arrow * [1, -1] if shape == 'right': coords = right_half_arrow elif shape == 'full': # The half-arrows contain the midpoint of the stem, # which we can omit from the full arrow. Including it # twice caused a problem with xpdf. coords = np.concatenate([left_half_arrow[:-1], right_half_arrow[-2::-1]]) else: raise ValueError("Got unknown shape: %s" % shape) if distance != 0: cx = dx / distance sx = dy / distance else: # Account for division by zero cx, sx = 0, 1 M = [[cx, sx], [-sx, cx]] verts = np.dot(coords, M) + (x + dx, y + dy) Polygon.__init__(self, list(map(tuple, verts)), closed=True, **kwargs) docstring.interpd.update({"FancyArrow": FancyArrow.__init__.__doc__}) class YAArrow(Patch): """ Yet another arrow class. This is an arrow that is defined in display space and has a tip at *x1*, *y1* and a base at *x2*, *y2*. """ def __str__(self): return "YAArrow()" @docstring.dedent_interpd def __init__(self, figure, xytip, xybase, width=4, frac=0.1, headwidth=12, **kwargs): """ Constructor arguments: *xytip* (*x*, *y*) location of arrow tip *xybase* (*x*, *y*) location the arrow base mid point *figure* The :class:`~matplotlib.figure.Figure` instance (fig.dpi) *width* The width of the arrow in points *frac* The fraction of the arrow length occupied by the head *headwidth* The width of the base of the arrow head in points Valid kwargs are: %(Patch)s """ self.xytip = xytip self.xybase = xybase self.width = width self.frac = frac self.headwidth = headwidth Patch.__init__(self, **kwargs) # Set self.figure after Patch.__init__, since it sets self.figure to # None self.figure = figure def get_path(self): # Since this is dpi dependent, we need to recompute the path # every time. # the base vertices x1, y1 = self.xytip x2, y2 = self.xybase k1 = self.width * self.figure.dpi / 72. / 2. k2 = self.headwidth * self.figure.dpi / 72. / 2. xb1, yb1, xb2, yb2 = self.getpoints(x1, y1, x2, y2, k1) # a point on the segment 20% of the distance from the tip to the base theta = math.atan2(y2 - y1, x2 - x1) r = math.sqrt((y2 - y1) ** 2. + (x2 - x1) ** 2.) xm = x1 + self.frac * r * math.cos(theta) ym = y1 + self.frac * r * math.sin(theta) xc1, yc1, xc2, yc2 = self.getpoints(x1, y1, xm, ym, k1) xd1, yd1, xd2, yd2 = self.getpoints(x1, y1, xm, ym, k2) xs = self.convert_xunits([xb1, xb2, xc2, xd2, x1, xd1, xc1, xb1]) ys = self.convert_yunits([yb1, yb2, yc2, yd2, y1, yd1, yc1, yb1]) return Path(np.column_stack([xs, ys]), closed=True) def get_patch_transform(self): return transforms.IdentityTransform() def getpoints(self, x1, y1, x2, y2, k): """ For line segment defined by (*x1*, *y1*) and (*x2*, *y2*) return the points on the line that is perpendicular to the line and intersects (*x2*, *y2*) and the distance from (*x2*, *y2*) of the returned points is *k*. """ x1, y1, x2, y2, k = map(float, (x1, y1, x2, y2, k)) if y2 - y1 == 0: return x2, y2 + k, x2, y2 - k elif x2 - x1 == 0: return x2 + k, y2, x2 - k, y2 m = (y2 - y1) / (x2 - x1) pm = -1. / m a = 1 b = -2 * y2 c = y2 ** 2. - k ** 2. * pm ** 2. / (1. + pm ** 2.) y3a = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) x3a = (y3a - y2) / pm + x2 y3b = (-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) x3b = (y3b - y2) / pm + x2 return x3a, y3a, x3b, y3b class CirclePolygon(RegularPolygon): """ A polygon-approximation of a circle patch. """ def __str__(self): return "CirclePolygon(%d,%d)" % self.center @docstring.dedent_interpd def __init__(self, xy, radius=5, resolution=20, # the number of vertices ** kwargs): """ Create a circle at *xy* = (*x*, *y*) with given *radius*. This circle is approximated by a regular polygon with *resolution* sides. For a smoother circle drawn with splines, see :class:`~matplotlib.patches.Circle`. Valid kwargs are: %(Patch)s """ RegularPolygon.__init__(self, xy, resolution, radius, orientation=0, **kwargs) class Ellipse(Patch): """ A scale-free ellipse. """ def __str__(self): pars = (self.center[0], self.center[1], self.width, self.height, self.angle) fmt = "Ellipse(xy=(%s, %s), width=%s, height=%s, angle=%s)" return fmt % pars @docstring.dedent_interpd def __init__(self, xy, width, height, angle=0.0, **kwargs): """ *xy* center of ellipse *width* total length (diameter) of horizontal axis *height* total length (diameter) of vertical axis *angle* rotation in degrees (anti-clockwise) Valid kwargs are: %(Patch)s """ Patch.__init__(self, **kwargs) self.center = xy self.width, self.height = width, height self.angle = angle self._path = Path.unit_circle() # Note: This cannot be calculated until this is added to an Axes self._patch_transform = transforms.IdentityTransform() def _recompute_transform(self): """NOTE: This cannot be called until after this has been added to an Axes, otherwise unit conversion will fail. This makes it very important to call the accessor method and not directly access the transformation member variable. """ center = (self.convert_xunits(self.center[0]), self.convert_yunits(self.center[1])) width = self.convert_xunits(self.width) height = self.convert_yunits(self.height) self._patch_transform = transforms.Affine2D() \ .scale(width * 0.5, height * 0.5) \ .rotate_deg(self.angle) \ .translate(*center) def get_path(self): """ Return the vertices of the rectangle """ return self._path def get_patch_transform(self): self._recompute_transform() return self._patch_transform class Circle(Ellipse): """ A circle patch. """ def __str__(self): pars = self.center[0], self.center[1], self.radius fmt = "Circle(xy=(%g, %g), radius=%g)" return fmt % pars @docstring.dedent_interpd def __init__(self, xy, radius=5, **kwargs): """ Create true circle at center *xy* = (*x*, *y*) with given *radius*. Unlike :class:`~matplotlib.patches.CirclePolygon` which is a polygonal approximation, this uses Bézier splines and is much closer to a scale-free circle. Valid kwargs are: %(Patch)s """ Ellipse.__init__(self, xy, radius * 2, radius * 2, **kwargs) self.radius = radius def set_radius(self, radius): """ Set the radius of the circle ACCEPTS: float """ self.width = self.height = 2 * radius self.stale = True def get_radius(self): 'return the radius of the circle' return self.width / 2. radius = property(get_radius, set_radius) class Arc(Ellipse): """ An elliptical arc. Because it performs various optimizations, it can not be filled. The arc must be used in an :class:`~matplotlib.axes.Axes` instance---it can not be added directly to a :class:`~matplotlib.figure.Figure`---because it is optimized to only render the segments that are inside the axes bounding box with high resolution. """ def __str__(self): pars = (self.center[0], self.center[1], self.width, self.height, self.angle, self.theta1, self.theta2) fmt = ("Arc(xy=(%g, %g), width=%g, " "height=%g, angle=%g, theta1=%g, theta2=%g)") return fmt % pars @docstring.dedent_interpd def __init__(self, xy, width, height, angle=0.0, theta1=0.0, theta2=360.0, **kwargs): """ The following args are supported: *xy* center of ellipse *width* length of horizontal axis *height* length of vertical axis *angle* rotation in degrees (anti-clockwise) *theta1* starting angle of the arc in degrees *theta2* ending angle of the arc in degrees If *theta1* and *theta2* are not provided, the arc will form a complete ellipse. Valid kwargs are: %(Patch)s """ fill = kwargs.setdefault('fill', False) if fill: raise ValueError("Arc objects can not be filled") Ellipse.__init__(self, xy, width, height, angle, **kwargs) self.theta1 = theta1 self.theta2 = theta2 @artist.allow_rasterization def draw(self, renderer): """ Ellipses are normally drawn using an approximation that uses eight cubic bezier splines. The error of this approximation is 1.89818e-6, according to this unverified source: Lancaster, Don. Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines. http://www.tinaja.com/glib/ellipse4.pdf There is a use case where very large ellipses must be drawn with very high accuracy, and it is too expensive to render the entire ellipse with enough segments (either splines or line segments). Therefore, in the case where either radius of the ellipse is large enough that the error of the spline approximation will be visible (greater than one pixel offset from the ideal), a different technique is used. In that case, only the visible parts of the ellipse are drawn, with each visible arc using a fixed number of spline segments (8). The algorithm proceeds as follows: 1. The points where the ellipse intersects the axes bounding box are located. (This is done be performing an inverse transformation on the axes bbox such that it is relative to the unit circle -- this makes the intersection calculation much easier than doing rotated ellipse intersection directly). This uses the "line intersecting a circle" algorithm from: Vince, John. Geometry for Computer Graphics: Formulae, Examples & Proofs. London: Springer-Verlag, 2005. 2. The angles of each of the intersection points are calculated. 3. Proceeding counterclockwise starting in the positive x-direction, each of the visible arc-segments between the pairs of vertices are drawn using the bezier arc approximation technique implemented in :meth:`matplotlib.path.Path.arc`. """ if not hasattr(self, 'axes'): raise RuntimeError('Arcs can only be used in Axes instances') self._recompute_transform() width = self.convert_xunits(self.width) height = self.convert_yunits(self.height) # If the width and height of ellipse are not equal, take into account # stretching when calculating angles to draw between def theta_stretch(theta, scale): theta = np.deg2rad(theta) x = np.cos(theta) y = np.sin(theta) return np.rad2deg(np.arctan2(scale * y, x)) theta1 = theta_stretch(self.theta1, width / height) theta2 = theta_stretch(self.theta2, width / height) # Get width and height in pixels width, height = self.get_transform().transform_point((width, height)) inv_error = (1.0 / 1.89818e-6) * 0.5 if width < inv_error and height < inv_error: self._path = Path.arc(theta1, theta2) return Patch.draw(self, renderer) def iter_circle_intersect_on_line(x0, y0, x1, y1): dx = x1 - x0 dy = y1 - y0 dr2 = dx * dx + dy * dy D = x0 * y1 - x1 * y0 D2 = D * D discrim = dr2 - D2 # Single (tangential) intersection if discrim == 0.0: x = (D * dy) / dr2 y = (-D * dx) / dr2 yield x, y elif discrim > 0.0: # The definition of "sign" here is different from # np.sign: we never want to get 0.0 if dy < 0.0: sign_dy = -1.0 else: sign_dy = 1.0 sqrt_discrim = np.sqrt(discrim) for sign in (1., -1.): x = (D * dy + sign * sign_dy * dx * sqrt_discrim) / dr2 y = (-D * dx + sign * np.abs(dy) * sqrt_discrim) / dr2 yield x, y def iter_circle_intersect_on_line_seg(x0, y0, x1, y1): epsilon = 1e-9 if x1 < x0: x0e, x1e = x1, x0 else: x0e, x1e = x0, x1 if y1 < y0: y0e, y1e = y1, y0 else: y0e, y1e = y0, y1 x0e -= epsilon y0e -= epsilon x1e += epsilon y1e += epsilon for x, y in iter_circle_intersect_on_line(x0, y0, x1, y1): if x >= x0e and x <= x1e and y >= y0e and y <= y1e: yield x, y # Transforms the axes box_path so that it is relative to the unit # circle in the same way that it is relative to the desired # ellipse. box_path = Path.unit_rectangle() box_path_transform = transforms.BboxTransformTo(self.axes.bbox) + \ self.get_transform().inverted() box_path = box_path.transformed(box_path_transform) thetas = set() # For each of the point pairs, there is a line segment for p0, p1 in zip(box_path.vertices[:-1], box_path.vertices[1:]): x0, y0 = p0 x1, y1 = p1 for x, y in iter_circle_intersect_on_line_seg(x0, y0, x1, y1): theta = np.arccos(x) if y < 0: theta = 2 * np.pi - theta # Convert radians to angles theta = np.rad2deg(theta) if theta1 < theta < theta2: thetas.add(theta) thetas = sorted(thetas) + [theta2] last_theta = theta1 theta1_rad = np.deg2rad(theta1) inside = box_path.contains_point((np.cos(theta1_rad), np.sin(theta1_rad))) # save original path path_original = self._path for theta in thetas: if inside: self._path = Path.arc(last_theta, theta, 8) Patch.draw(self, renderer) inside = False else: inside = True last_theta = theta # restore original path self._path = path_original def bbox_artist(artist, renderer, props=None, fill=True): """ This is a debug function to draw a rectangle around the bounding box returned by :meth:`~matplotlib.artist.Artist.get_window_extent` of an artist, to test whether the artist is returning the correct bbox. *props* is a dict of rectangle props with the additional property 'pad' that sets the padding around the bbox in points. """ if props is None: props = {} props = props.copy() # don't want to alter the pad externally pad = props.pop('pad', 4) pad = renderer.points_to_pixels(pad) bbox = artist.get_window_extent(renderer) l, b, w, h = bbox.bounds l -= pad / 2. b -= pad / 2. w += pad h += pad r = Rectangle(xy=(l, b), width=w, height=h, fill=fill, ) r.set_transform(transforms.IdentityTransform()) r.set_clip_on(False) r.update(props) r.draw(renderer) def draw_bbox(bbox, renderer, color='k', trans=None): """ This is a debug function to draw a rectangle around the bounding box returned by :meth:`~matplotlib.artist.Artist.get_window_extent` of an artist, to test whether the artist is returning the correct bbox. """ l, b, w, h = bbox.bounds r = Rectangle(xy=(l, b), width=w, height=h, edgecolor=color, fill=False, ) if trans is not None: r.set_transform(trans) r.set_clip_on(False) r.draw(renderer) def _pprint_table(_table, leadingspace=2): """ Given the list of list of strings, return a string of REST table format. """ if leadingspace: pad = ' ' * leadingspace else: pad = '' columns = [[] for cell in _table[0]] for row in _table: for column, cell in zip(columns, row): column.append(cell) col_len = [max(len(cell) for cell in column) for column in columns] lines = [] table_formatstr = pad + ' '.join([('=' * cl) for cl in col_len]) lines.append('') lines.append(table_formatstr) lines.append(pad + ' '.join([cell.ljust(cl) for cell, cl in zip(_table[0], col_len)])) lines.append(table_formatstr) lines.extend([(pad + ' '.join([cell.ljust(cl) for cell, cl in zip(row, col_len)])) for row in _table[1:]]) lines.append(table_formatstr) lines.append('') return "\n".join(lines) def _pprint_styles(_styles): """ A helper function for the _Style class. Given the dictionary of (stylename : styleclass), return a formatted string listing all the styles. Used to update the documentation. """ import inspect _table = [["Class", "Name", "Attrs"]] for name, cls in sorted(_styles.items()): if six.PY2: args, varargs, varkw, defaults = inspect.getargspec(cls.__init__) else: (args, varargs, varkw, defaults, kwonlyargs, kwonlydefs, annotations) = inspect.getfullargspec(cls.__init__) if defaults: args = [(argname, argdefault) for argname, argdefault in zip(args[1:], defaults)] else: args = None if args is None: argstr = 'None' else: argstr = ",".join([("%s=%s" % (an, av)) for an, av in args]) # adding ``quotes`` since - and | have special meaning in reST _table.append([cls.__name__, "``%s``" % name, argstr]) return _pprint_table(_table) def _simpleprint_styles(_styles): """ A helper function for the _Style class. Given the dictionary of (stylename : styleclass), return a string rep of the list of keys. Used to update the documentation. """ return "[{}]".format("|".join(map(" '{}' ".format, sorted(_styles)))) class _Style(object): """ A base class for the Styles. It is meant to be a container class, where actual styles are declared as subclass of it, and it provides some helper functions. """ def __new__(self, stylename, **kw): """ return the instance of the subclass with the given style name. """ # the "class" should have the _style_list attribute, which is # a dictionary of stylname, style class paie. _list = stylename.replace(" ", "").split(",") _name = _list[0].lower() try: _cls = self._style_list[_name] except KeyError: raise ValueError("Unknown style : %s" % stylename) try: _args_pair = [cs.split("=") for cs in _list[1:]] _args = {k: float(v) for k, v in _args_pair} except ValueError: raise ValueError("Incorrect style argument : %s" % stylename) _args.update(kw) return _cls(**_args) @classmethod def get_styles(klass): """ A class method which returns a dictionary of available styles. """ return klass._style_list @classmethod def pprint_styles(klass): """ A class method which returns a string of the available styles. """ return _pprint_styles(klass._style_list) @classmethod def register(klass, name, style): """ Register a new style. """ if not issubclass(style, klass._Base): raise ValueError("%s must be a subclass of %s" % (style, klass._Base)) klass._style_list[name] = style class BoxStyle(_Style): """ :class:`BoxStyle` is a container class which defines several boxstyle classes, which are used for :class:`FancyBboxPatch`. A style object can be created as:: BoxStyle.Round(pad=0.2) or:: BoxStyle("Round", pad=0.2) or:: BoxStyle("Round, pad=0.2") Following boxstyle classes are defined. %(AvailableBoxstyles)s An instance of any boxstyle class is an callable object, whose call signature is:: __call__(self, x0, y0, width, height, mutation_size, aspect_ratio=1.) and returns a :class:`Path` instance. *x0*, *y0*, *width* and *height* specify the location and size of the box to be drawn. *mutation_scale* determines the overall size of the mutation (by which I mean the transformation of the rectangle to the fancy box). *mutation_aspect* determines the aspect-ratio of the mutation. """ _style_list = {} class _Base(object): """ :class:`BBoxTransmuterBase` and its derivatives are used to make a fancy box around a given rectangle. The :meth:`__call__` method returns the :class:`~matplotlib.path.Path` of the fancy box. This class is not an artist and actual drawing of the fancy box is done by the :class:`FancyBboxPatch` class. """ # The derived classes are required to be able to be initialized # w/o arguments, i.e., all its argument (except self) must have # the default values. def __init__(self): """ initializtion. """ super(BoxStyle._Base, self).__init__() def transmute(self, x0, y0, width, height, mutation_size): """ The transmute method is a very core of the :class:`BboxTransmuter` class and must be overridden in the subclasses. It receives the location and size of the rectangle, and the mutation_size, with which the amount of padding and etc. will be scaled. It returns a :class:`~matplotlib.path.Path` instance. """ raise NotImplementedError('Derived must override') def __call__(self, x0, y0, width, height, mutation_size, aspect_ratio=1.): """ Given the location and size of the box, return the path of the box around it. - *x0*, *y0*, *width*, *height* : location and size of the box - *mutation_size* : a reference scale for the mutation. - *aspect_ratio* : aspect-ration for the mutation. """ # The __call__ method is a thin wrapper around the transmute method # and take care of the aspect. if aspect_ratio is not None: # Squeeze the given height by the aspect_ratio y0, height = y0 / aspect_ratio, height / aspect_ratio # call transmute method with squeezed height. path = self.transmute(x0, y0, width, height, mutation_size) vertices, codes = path.vertices, path.codes # Restore the height vertices[:, 1] = vertices[:, 1] * aspect_ratio return Path(vertices, codes) else: return self.transmute(x0, y0, width, height, mutation_size) def __reduce__(self): # because we have decided to nest these classes, we need to # add some more information to allow instance pickling. return (cbook._NestedClassGetter(), (BoxStyle, self.__class__.__name__), self.__dict__ ) class Square(_Base): """ A simple square box. """ def __init__(self, pad=0.3): """ *pad* amount of padding """ self.pad = pad super(BoxStyle.Square, self).__init__() def transmute(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad # width and height with padding added. width, height = width + 2*pad, height + 2*pad # boundary of the padded box x0, y0 = x0 - pad, y0 - pad, x1, y1 = x0 + width, y0 + height vertices = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] codes = [Path.MOVETO] + [Path.LINETO] * 3 + [Path.CLOSEPOLY] return Path(vertices, codes) _style_list["square"] = Square class Circle(_Base): """A simple circle box.""" def __init__(self, pad=0.3): """ Parameters ---------- pad : float The amount of padding around the original box. """ self.pad = pad super(BoxStyle.Circle, self).__init__() def transmute(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad width, height = width + 2 * pad, height + 2 * pad # boundary of the padded box x0, y0 = x0 - pad, y0 - pad, return Path.circle((x0 + width / 2, y0 + height / 2), max(width, height) / 2) _style_list["circle"] = Circle class LArrow(_Base): """ (left) Arrow Box """ def __init__(self, pad=0.3): self.pad = pad super(BoxStyle.LArrow, self).__init__() def transmute(self, x0, y0, width, height, mutation_size): # padding pad = mutation_size * self.pad # width and height with padding added. width, height = width + 2. * pad, height + 2. * pad # boundary of the padded box x0, y0 = x0 - pad, y0 - pad, x1, y1 = x0 + width, y0 + height dx = (y1 - y0) / 2. dxx = dx * .5 # adjust x0. 1.4 <- sqrt(2) x0 = x0 + pad / 1.4 cp = [(x0 + dxx, y0), (x1, y0), (x1, y1), (x0 + dxx, y1), (x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx), (x0 + dxx, y0 - dxx), # arrow (x0 + dxx, y0), (x0 + dxx, y0)] com = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] path = Path(cp, com) return path _style_list["larrow"] = LArrow class RArrow(LArrow): """ (right) Arrow Box """ def __init__(self, pad=0.3): super(BoxStyle.RArrow, self).__init__(pad) def transmute(self, x0, y0, width, height, mutation_size): p = BoxStyle.LArrow.transmute(self, x0, y0, width, height, mutation_size) p.vertices[:, 0] = 2 * x0 + width - p.vertices[:, 0] return p _style_list["rarrow"] = RArrow class DArrow(_Base): """ (Double) Arrow Box """ # This source is copied from LArrow, # modified to add a right arrow to the bbox. def __init__(self, pad=0.3): self.pad = pad super(BoxStyle.DArrow, self).__init__() def transmute(self, x0, y0, width, height, mutation_size): # padding pad = mutation_size * self.pad # width and height with padding added. # The width is padded by the arrows, so we don't need to pad it. height = height + 2. * pad # boundary of the padded box x0, y0 = x0 - pad, y0 - pad x1, y1 = x0 + width, y0 + height dx = (y1 - y0)/2. dxx = dx * .5 # adjust x0. 1.4 <- sqrt(2) x0 = x0 + pad / 1.4 cp = [(x0 + dxx, y0), (x1, y0), # bot-segment (x1, y0 - dxx), (x1 + dx + dxx, y0 + dx), (x1, y1 + dxx), # right-arrow (x1, y1), (x0 + dxx, y1), # top-segment (x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx), (x0 + dxx, y0 - dxx), # left-arrow (x0 + dxx, y0), (x0 + dxx, y0)] # close-poly com = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] path = Path(cp, com) return path _style_list['darrow'] = DArrow class Round(_Base): """ A box with round corners. """ def __init__(self, pad=0.3, rounding_size=None): """ *pad* amount of padding *rounding_size* rounding radius of corners. *pad* if None """ self.pad = pad self.rounding_size = rounding_size super(BoxStyle.Round, self).__init__() def transmute(self, x0, y0, width, height, mutation_size): # padding pad = mutation_size * self.pad # size of the roudning corner if self.rounding_size: dr = mutation_size * self.rounding_size else: dr = pad width, height = width + 2. * pad, height + 2. * pad x0, y0 = x0 - pad, y0 - pad, x1, y1 = x0 + width, y0 + height # Round corners are implemented as quadratic bezier. e.g., # [(x0, y0-dr), (x0, y0), (x0+dr, y0)] for lower left corner. cp = [(x0 + dr, y0), (x1 - dr, y0), (x1, y0), (x1, y0 + dr), (x1, y1 - dr), (x1, y1), (x1 - dr, y1), (x0 + dr, y1), (x0, y1), (x0, y1 - dr), (x0, y0 + dr), (x0, y0), (x0 + dr, y0), (x0 + dr, y0)] com = [Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY] path = Path(cp, com) return path _style_list["round"] = Round class Round4(_Base): """ Another box with round edges. """ def __init__(self, pad=0.3, rounding_size=None): """ *pad* amount of padding *rounding_size* rounding size of edges. *pad* if None """ self.pad = pad self.rounding_size = rounding_size super(BoxStyle.Round4, self).__init__() def transmute(self, x0, y0, width, height, mutation_size): # padding pad = mutation_size * self.pad # roudning size. Use a half of the pad if not set. if self.rounding_size: dr = mutation_size * self.rounding_size else: dr = pad / 2. width, height = (width + 2. * pad - 2 * dr, height + 2. * pad - 2 * dr) x0, y0 = x0 - pad + dr, y0 - pad + dr, x1, y1 = x0 + width, y0 + height cp = [(x0, y0), (x0 + dr, y0 - dr), (x1 - dr, y0 - dr), (x1, y0), (x1 + dr, y0 + dr), (x1 + dr, y1 - dr), (x1, y1), (x1 - dr, y1 + dr), (x0 + dr, y1 + dr), (x0, y1), (x0 - dr, y1 - dr), (x0 - dr, y0 + dr), (x0, y0), (x0, y0)] com = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CLOSEPOLY] path = Path(cp, com) return path _style_list["round4"] = Round4 class Sawtooth(_Base): """ A sawtooth box. """ def __init__(self, pad=0.3, tooth_size=None): """ *pad* amount of padding *tooth_size* size of the sawtooth. pad* if None """ self.pad = pad self.tooth_size = tooth_size super(BoxStyle.Sawtooth, self).__init__() def _get_sawtooth_vertices(self, x0, y0, width, height, mutation_size): # padding pad = mutation_size * self.pad # size of sawtooth if self.tooth_size is None: tooth_size = self.pad * .5 * mutation_size else: tooth_size = self.tooth_size * mutation_size tooth_size2 = tooth_size / 2. width, height = (width + 2. * pad - tooth_size, height + 2. * pad - tooth_size) # the sizes of the vertical and horizontal sawtooth are # separately adjusted to fit the given box size. dsx_n = int(np.round((width - tooth_size) / (tooth_size * 2))) * 2 dsx = (width - tooth_size) / dsx_n dsy_n = int(np.round((height - tooth_size) / (tooth_size * 2))) * 2 dsy = (height - tooth_size) / dsy_n x0, y0 = x0 - pad + tooth_size2, y0 - pad + tooth_size2 x1, y1 = x0 + width, y0 + height bottom_saw_x = [x0] + \ [x0 + tooth_size2 + dsx * .5 * i for i in range(dsx_n * 2)] + \ [x1 - tooth_size2] bottom_saw_y = [y0] + \ [y0 - tooth_size2, y0, y0 + tooth_size2, y0] * dsx_n + \ [y0 - tooth_size2] right_saw_x = [x1] + \ [x1 + tooth_size2, x1, x1 - tooth_size2, x1] * dsx_n + \ [x1 + tooth_size2] right_saw_y = [y0] + \ [y0 + tooth_size2 + dsy * .5 * i for i in range(dsy_n * 2)] + \ [y1 - tooth_size2] top_saw_x = [x1] + \ [x1 - tooth_size2 - dsx * .5 * i for i in range(dsx_n * 2)] + \ [x0 + tooth_size2] top_saw_y = [y1] + \ [y1 + tooth_size2, y1, y1 - tooth_size2, y1] * dsx_n + \ [y1 + tooth_size2] left_saw_x = [x0] + \ [x0 - tooth_size2, x0, x0 + tooth_size2, x0] * dsy_n + \ [x0 - tooth_size2] left_saw_y = [y1] + \ [y1 - tooth_size2 - dsy * .5 * i for i in range(dsy_n * 2)] + \ [y0 + tooth_size2] saw_vertices = (list(zip(bottom_saw_x, bottom_saw_y)) + list(zip(right_saw_x, right_saw_y)) + list(zip(top_saw_x, top_saw_y)) + list(zip(left_saw_x, left_saw_y)) + [(bottom_saw_x[0], bottom_saw_y[0])]) return saw_vertices def transmute(self, x0, y0, width, height, mutation_size): saw_vertices = self._get_sawtooth_vertices(x0, y0, width, height, mutation_size) path = Path(saw_vertices, closed=True) return path _style_list["sawtooth"] = Sawtooth class Roundtooth(Sawtooth): """A rounded tooth box.""" def __init__(self, pad=0.3, tooth_size=None): """ *pad* amount of padding *tooth_size* size of the sawtooth. pad* if None """ super(BoxStyle.Roundtooth, self).__init__(pad, tooth_size) def transmute(self, x0, y0, width, height, mutation_size): saw_vertices = self._get_sawtooth_vertices(x0, y0, width, height, mutation_size) # Add a trailing vertex to allow us to close the polygon correctly saw_vertices = np.concatenate([np.array(saw_vertices), [saw_vertices[0]]], axis=0) codes = ([Path.MOVETO] + [Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1)//2) + [Path.CLOSEPOLY]) return Path(saw_vertices, codes) _style_list["roundtooth"] = Roundtooth if __doc__: # __doc__ could be None if -OO optimization is enabled __doc__ = cbook.dedent(__doc__) % \ {"AvailableBoxstyles": _pprint_styles(_style_list)} docstring.interpd.update( AvailableBoxstyles=_pprint_styles(BoxStyle._style_list), ListBoxstyles=_simpleprint_styles(BoxStyle._style_list)) class FancyBboxPatch(Patch): """ Draw a fancy box around a rectangle with lower left at *xy*=(*x*, *y*) with specified width and height. :class:`FancyBboxPatch` class is similar to :class:`Rectangle` class, but it draws a fancy box around the rectangle. The transformation of the rectangle box to the fancy box is delegated to the :class:`BoxTransmuterBase` and its derived classes. """ _edge_default = True def __str__(self): return self.__class__.__name__ \ + "(%g,%g;%gx%g)" % (self._x, self._y, self._width, self._height) @docstring.dedent_interpd def __init__(self, xy, width, height, boxstyle="round", bbox_transmuter=None, mutation_scale=1., mutation_aspect=None, **kwargs): """ *xy* = lower left corner *width*, *height* *boxstyle* determines what kind of fancy box will be drawn. It can be a string of the style name with a comma separated attribute, or an instance of :class:`BoxStyle`. Following box styles are available. %(AvailableBoxstyles)s *mutation_scale* : a value with which attributes of boxstyle (e.g., pad) will be scaled. default=1. *mutation_aspect* : The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None. Valid kwargs are: %(Patch)s """ Patch.__init__(self, **kwargs) self._x = xy[0] self._y = xy[1] self._width = width self._height = height if boxstyle == "custom": if bbox_transmuter is None: raise ValueError("bbox_transmuter argument is needed with " "custom boxstyle") self._bbox_transmuter = bbox_transmuter else: self.set_boxstyle(boxstyle) self._mutation_scale = mutation_scale self._mutation_aspect = mutation_aspect self.stale = True @docstring.dedent_interpd def set_boxstyle(self, boxstyle=None, **kw): """ Set the box style. *boxstyle* can be a string with boxstyle name with optional comma-separated attributes. Alternatively, the attrs can be provided as keywords:: set_boxstyle("round,pad=0.2") set_boxstyle("round", pad=0.2) Old attrs simply are forgotten. Without argument (or with *boxstyle* = None), it returns available box styles. The following boxstyles are available: %(AvailableBoxstyles)s ACCEPTS: %(ListBoxstyles)s """ if boxstyle is None: return BoxStyle.pprint_styles() if isinstance(boxstyle, BoxStyle._Base) or callable(boxstyle): self._bbox_transmuter = boxstyle else: self._bbox_transmuter = BoxStyle(boxstyle, **kw) self.stale = True def set_mutation_scale(self, scale): """ Set the mutation scale. ACCEPTS: float """ self._mutation_scale = scale self.stale = True def get_mutation_scale(self): """ Return the mutation scale. """ return self._mutation_scale def set_mutation_aspect(self, aspect): """ Set the aspect ratio of the bbox mutation. ACCEPTS: float """ self._mutation_aspect = aspect self.stale = True def get_mutation_aspect(self): """ Return the aspect ratio of the bbox mutation. """ return self._mutation_aspect def get_boxstyle(self): "Return the boxstyle object" return self._bbox_transmuter def get_path(self): """ Return the mutated path of the rectangle """ _path = self.get_boxstyle()(self._x, self._y, self._width, self._height, self.get_mutation_scale(), self.get_mutation_aspect()) return _path # Following methods are borrowed from the Rectangle class. def get_x(self): "Return the left coord of the rectangle" return self._x def get_y(self): "Return the bottom coord of the rectangle" return self._y def get_width(self): "Return the width of the rectangle" return self._width def get_height(self): "Return the height of the rectangle" return self._height def set_x(self, x): """ Set the left coord of the rectangle ACCEPTS: float """ self._x = x self.stale = True def set_y(self, y): """ Set the bottom coord of the rectangle ACCEPTS: float """ self._y = y self.stale = True def set_width(self, w): """ Set the width rectangle ACCEPTS: float """ self._width = w self.stale = True def set_height(self, h): """ Set the width rectangle ACCEPTS: float """ self._height = h self.stale = True def set_bounds(self, *args): """ Set the bounds of the rectangle: l,b,w,h ACCEPTS: (left, bottom, width, height) """ if len(args) == 0: l, b, w, h = args[0] else: l, b, w, h = args self._x = l self._y = b self._width = w self._height = h self.stale = True def get_bbox(self): return transforms.Bbox.from_bounds(self._x, self._y, self._width, self._height) class ConnectionStyle(_Style): """ :class:`ConnectionStyle` is a container class which defines several connectionstyle classes, which is used to create a path between two points. These are mainly used with :class:`FancyArrowPatch`. A connectionstyle object can be either created as:: ConnectionStyle.Arc3(rad=0.2) or:: ConnectionStyle("Arc3", rad=0.2) or:: ConnectionStyle("Arc3, rad=0.2") The following classes are defined %(AvailableConnectorstyles)s An instance of any connection style class is an callable object, whose call signature is:: __call__(self, posA, posB, patchA=None, patchB=None, shrinkA=2., shrinkB=2.) and it returns a :class:`Path` instance. *posA* and *posB* are tuples of x,y coordinates of the two points to be connected. *patchA* (or *patchB*) is given, the returned path is clipped so that it start (or end) from the boundary of the patch. The path is further shrunk by *shrinkA* (or *shrinkB*) which is given in points. """ _style_list = {} class _Base(object): """ A base class for connectionstyle classes. The subclass needs to implement a *connect* method whose call signature is:: connect(posA, posB) where posA and posB are tuples of x, y coordinates to be connected. The method needs to return a path connecting two points. This base class defines a __call__ method, and a few helper methods. """ class SimpleEvent: def __init__(self, xy): self.x, self.y = xy def _clip(self, path, patchA, patchB): """ Clip the path to the boundary of the patchA and patchB. The starting point of the path needed to be inside of the patchA and the end point inside the patch B. The *contains* methods of each patch object is utilized to test if the point is inside the path. """ if patchA: def insideA(xy_display): xy_event = ConnectionStyle._Base.SimpleEvent(xy_display) return patchA.contains(xy_event)[0] try: left, right = split_path_inout(path, insideA) except ValueError: right = path path = right if patchB: def insideB(xy_display): xy_event = ConnectionStyle._Base.SimpleEvent(xy_display) return patchB.contains(xy_event)[0] try: left, right = split_path_inout(path, insideB) except ValueError: left = path path = left return path def _shrink(self, path, shrinkA, shrinkB): """ Shrink the path by fixed size (in points) with shrinkA and shrinkB """ if shrinkA: x, y = path.vertices[0] insideA = inside_circle(x, y, shrinkA) try: left, right = split_path_inout(path, insideA) path = right except ValueError: pass if shrinkB: x, y = path.vertices[-1] insideB = inside_circle(x, y, shrinkB) try: left, right = split_path_inout(path, insideB) path = left except ValueError: pass return path def __call__(self, posA, posB, shrinkA=2., shrinkB=2., patchA=None, patchB=None): """ Calls the *connect* method to create a path between *posA* and *posB*. The path is clipped and shrunken. """ path = self.connect(posA, posB) clipped_path = self._clip(path, patchA, patchB) shrunk_path = self._shrink(clipped_path, shrinkA, shrinkB) return shrunk_path def __reduce__(self): # because we have decided to nest these classes, we need to # add some more information to allow instance pickling. return (cbook._NestedClassGetter(), (ConnectionStyle, self.__class__.__name__), self.__dict__ ) class Arc3(_Base): """ Creates a simple quadratic bezier curve between two points. The curve is created so that the middle control point (C1) is located at the same distance from the start (C0) and end points(C2) and the distance of the C1 to the line connecting C0-C2 is *rad* times the distance of C0-C2. """ def __init__(self, rad=0.): """ *rad* curvature of the curve. """ self.rad = rad def connect(self, posA, posB): x1, y1 = posA x2, y2 = posB x12, y12 = (x1 + x2) / 2., (y1 + y2) / 2. dx, dy = x2 - x1, y2 - y1 f = self.rad cx, cy = x12 + f * dy, y12 - f * dx vertices = [(x1, y1), (cx, cy), (x2, y2)] codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3] return Path(vertices, codes) _style_list["arc3"] = Arc3 class Angle3(_Base): """ Creates a simple quadratic bezier curve between two points. The middle control points is placed at the intersecting point of two lines which crosses the start (or end) point and has a angle of angleA (or angleB). """ def __init__(self, angleA=90, angleB=0): """ *angleA* starting angle of the path *angleB* ending angle of the path """ self.angleA = angleA self.angleB = angleB def connect(self, posA, posB): x1, y1 = posA x2, y2 = posB cosA = math.cos(math.radians(self.angleA)) sinA = math.sin(math.radians(self.angleA)) cosB = math.cos(math.radians(self.angleB)) sinB = math.sin(math.radians(self.angleB)) cx, cy = get_intersection(x1, y1, cosA, sinA, x2, y2, cosB, sinB) vertices = [(x1, y1), (cx, cy), (x2, y2)] codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3] return Path(vertices, codes) _style_list["angle3"] = Angle3 class Angle(_Base): """ Creates a picewise continuous quadratic bezier path between two points. The path has a one passing-through point placed at the intersecting point of two lines which crosses the start (or end) point and has a angle of angleA (or angleB). The connecting edges are rounded with *rad*. """ def __init__(self, angleA=90, angleB=0, rad=0.): """ *angleA* starting angle of the path *angleB* ending angle of the path *rad* rounding radius of the edge """ self.angleA = angleA self.angleB = angleB self.rad = rad def connect(self, posA, posB): x1, y1 = posA x2, y2 = posB cosA = math.cos(math.radians(self.angleA)) sinA = math.sin(math.radians(self.angleA)) cosB = math.cos(math.radians(self.angleB)) sinB = math.sin(math.radians(self.angleB)) cx, cy = get_intersection(x1, y1, cosA, sinA, x2, y2, cosB, sinB) vertices = [(x1, y1)] codes = [Path.MOVETO] if self.rad == 0.: vertices.append((cx, cy)) codes.append(Path.LINETO) else: dx1, dy1 = x1 - cx, y1 - cy d1 = (dx1 ** 2 + dy1 ** 2) ** .5 f1 = self.rad / d1 dx2, dy2 = x2 - cx, y2 - cy d2 = (dx2 ** 2 + dy2 ** 2) ** .5 f2 = self.rad / d2 vertices.extend([(cx + dx1 * f1, cy + dy1 * f1), (cx, cy), (cx + dx2 * f2, cy + dy2 * f2)]) codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3]) vertices.append((x2, y2)) codes.append(Path.LINETO) return Path(vertices, codes) _style_list["angle"] = Angle class Arc(_Base): """ Creates a picewise continuous quadratic bezier path between two points. The path can have two passing-through points, a point placed at the distance of armA and angle of angleA from point A, another point with respect to point B. The edges are rounded with *rad*. """ def __init__(self, angleA=0, angleB=0, armA=None, armB=None, rad=0.): """ *angleA* : starting angle of the path *angleB* : ending angle of the path *armA* : length of the starting arm *armB* : length of the ending arm *rad* : rounding radius of the edges """ self.angleA = angleA self.angleB = angleB self.armA = armA self.armB = armB self.rad = rad def connect(self, posA, posB): x1, y1 = posA x2, y2 = posB vertices = [(x1, y1)] rounded = [] codes = [Path.MOVETO] if self.armA: cosA = math.cos(math.radians(self.angleA)) sinA = math.sin(math.radians(self.angleA)) # x_armA, y_armB d = self.armA - self.rad rounded.append((x1 + d * cosA, y1 + d * sinA)) d = self.armA rounded.append((x1 + d * cosA, y1 + d * sinA)) if self.armB: cosB = math.cos(math.radians(self.angleB)) sinB = math.sin(math.radians(self.angleB)) x_armB, y_armB = x2 + self.armB * cosB, y2 + self.armB * sinB if rounded: xp, yp = rounded[-1] dx, dy = x_armB - xp, y_armB - yp dd = (dx * dx + dy * dy) ** .5 rounded.append((xp + self.rad * dx / dd, yp + self.rad * dy / dd)) vertices.extend(rounded) codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3]) else: xp, yp = vertices[-1] dx, dy = x_armB - xp, y_armB - yp dd = (dx * dx + dy * dy) ** .5 d = dd - self.rad rounded = [(xp + d * dx / dd, yp + d * dy / dd), (x_armB, y_armB)] if rounded: xp, yp = rounded[-1] dx, dy = x2 - xp, y2 - yp dd = (dx * dx + dy * dy) ** .5 rounded.append((xp + self.rad * dx / dd, yp + self.rad * dy / dd)) vertices.extend(rounded) codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3]) vertices.append((x2, y2)) codes.append(Path.LINETO) return Path(vertices, codes) _style_list["arc"] = Arc class Bar(_Base): """ A line with *angle* between A and B with *armA* and *armB*. One of the arms is extended so that they are connected in a right angle. The length of armA is determined by (*armA* + *fraction* x AB distance). Same for armB. """ def __init__(self, armA=0., armB=0., fraction=0.3, angle=None): """ Parameters ---------- armA : float minimum length of armA armB : float minimum length of armB fraction : float a fraction of the distance between two points that will be added to armA and armB. angle : float or None angle of the connecting line (if None, parallel to A and B) """ self.armA = armA self.armB = armB self.fraction = fraction self.angle = angle def connect(self, posA, posB): x1, y1 = posA x20, y20 = x2, y2 = posB theta1 = math.atan2(y2 - y1, x2 - x1) dx, dy = x2 - x1, y2 - y1 dd = (dx * dx + dy * dy) ** .5 ddx, ddy = dx / dd, dy / dd armA, armB = self.armA, self.armB if self.angle is not None: theta0 = np.deg2rad(self.angle) dtheta = theta1 - theta0 dl = dd * math.sin(dtheta) dL = dd * math.cos(dtheta) x2, y2 = x1 + dL * math.cos(theta0), y1 + dL * math.sin(theta0) armB = armB - dl # update dx, dy = x2 - x1, y2 - y1 dd2 = (dx * dx + dy * dy) ** .5 ddx, ddy = dx / dd2, dy / dd2 else: dl = 0. arm = max(armA, armB) f = self.fraction * dd + arm cx1, cy1 = x1 + f * ddy, y1 - f * ddx cx2, cy2 = x2 + f * ddy, y2 - f * ddx vertices = [(x1, y1), (cx1, cy1), (cx2, cy2), (x20, y20)] codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO] return Path(vertices, codes) _style_list["bar"] = Bar if __doc__: __doc__ = cbook.dedent(__doc__) % \ {"AvailableConnectorstyles": _pprint_styles(_style_list)} def _point_along_a_line(x0, y0, x1, y1, d): """ find a point along a line connecting (x0, y0) -- (x1, y1) whose distance from (x0, y0) is d. """ dx, dy = x0 - x1, y0 - y1 ff = d / (dx * dx + dy * dy) ** .5 x2, y2 = x0 - ff * dx, y0 - ff * dy return x2, y2 class ArrowStyle(_Style): """ :class:`ArrowStyle` is a container class which defines several arrowstyle classes, which is used to create an arrow path along a given path. These are mainly used with :class:`FancyArrowPatch`. A arrowstyle object can be either created as:: ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.4) or:: ArrowStyle("Fancy", head_length=.4, head_width=.4, tail_width=.4) or:: ArrowStyle("Fancy, head_length=.4, head_width=.4, tail_width=.4") The following classes are defined %(AvailableArrowstyles)s An instance of any arrow style class is a callable object, whose call signature is:: __call__(self, path, mutation_size, linewidth, aspect_ratio=1.) and it returns a tuple of a :class:`Path` instance and a boolean value. *path* is a :class:`Path` instance along which the arrow will be drawn. *mutation_size* and *aspect_ratio* have the same meaning as in :class:`BoxStyle`. *linewidth* is a line width to be stroked. This is meant to be used to correct the location of the head so that it does not overshoot the destination point, but not all classes support it. """ _style_list = {} class _Base(object): """ Arrow Transmuter Base class ArrowTransmuterBase and its derivatives are used to make a fancy arrow around a given path. The __call__ method returns a path (which will be used to create a PathPatch instance) and a boolean value indicating the path is open therefore is not fillable. This class is not an artist and actual drawing of the fancy arrow is done by the FancyArrowPatch class. """ # The derived classes are required to be able to be initialized # w/o arguments, i.e., all its argument (except self) must have # the default values. @staticmethod def ensure_quadratic_bezier(path): """ Some ArrowStyle class only wokrs with a simple quaratic bezier curve (created with Arc3Connetion or Angle3Connector). This static method is to check if the provided path is a simple quadratic bezier curve and returns its control points if true. """ segments = list(path.iter_segments()) if (len(segments) != 2 or segments[0][1] != Path.MOVETO or segments[1][1] != Path.CURVE3): raise ValueError( "'path' it's not a valid quadratic Bezier curve") return list(segments[0][0]) + list(segments[1][0]) def transmute(self, path, mutation_size, linewidth): """ The transmute method is the very core of the ArrowStyle class and must be overridden in the subclasses. It receives the path object along which the arrow will be drawn, and the mutation_size, with which the arrow head etc. will be scaled. The linewidth may be used to adjust the path so that it does not pass beyond the given points. It returns a tuple of a Path instance and a boolean. The boolean value indicate whether the path can be filled or not. The return value can also be a list of paths and list of booleans of a same length. """ raise NotImplementedError('Derived must override') def __call__(self, path, mutation_size, linewidth, aspect_ratio=1.): """ The __call__ method is a thin wrapper around the transmute method and take care of the aspect ratio. """ path = make_path_regular(path) if aspect_ratio is not None: # Squeeze the given height by the aspect_ratio vertices, codes = path.vertices[:], path.codes[:] # Squeeze the height vertices[:, 1] = vertices[:, 1] / aspect_ratio path_shrunk = Path(vertices, codes) # call transmute method with squeezed height. path_mutated, fillable = self.transmute(path_shrunk, linewidth, mutation_size) if cbook.iterable(fillable): path_list = [] for p in zip(path_mutated): v, c = p.vertices, p.codes # Restore the height v[:, 1] = v[:, 1] * aspect_ratio path_list.append(Path(v, c)) return path_list, fillable else: return path_mutated, fillable else: return self.transmute(path, mutation_size, linewidth) def __reduce__(self): # because we have decided to nest these classes, we need to # add some more information to allow instance pickling. return (cbook._NestedClassGetter(), (ArrowStyle, self.__class__.__name__), self.__dict__ ) class _Curve(_Base): """ A simple arrow which will work with any path instance. The returned path is simply concatenation of the original path + at most two paths representing the arrow head at the begin point and the at the end point. The arrow heads can be either open or closed. """ def __init__(self, beginarrow=None, endarrow=None, fillbegin=False, fillend=False, head_length=.2, head_width=.1): """ The arrows are drawn if *beginarrow* and/or *endarrow* are true. *head_length* and *head_width* determines the size of the arrow relative to the *mutation scale*. The arrowhead at the begin (or end) is closed if fillbegin (or fillend) is True. """ self.beginarrow, self.endarrow = beginarrow, endarrow self.head_length, self.head_width = head_length, head_width self.fillbegin, self.fillend = fillbegin, fillend super(ArrowStyle._Curve, self).__init__() def _get_arrow_wedge(self, x0, y0, x1, y1, head_dist, cos_t, sin_t, linewidth ): """ Return the paths for arrow heads. Since arrow lines are drawn with capstyle=projected, The arrow goes beyond the desired point. This method also returns the amount of the path to be shrunken so that it does not overshoot. """ # arrow from x0, y0 to x1, y1 dx, dy = x0 - x1, y0 - y1 cp_distance = np.hypot(dx, dy) # pad_projected : amount of pad to account the # overshooting of the projection of the wedge pad_projected = (.5 * linewidth / sin_t) # Account for division by zero if cp_distance == 0: cp_distance = 1 # apply pad for projected edge ddx = pad_projected * dx / cp_distance ddy = pad_projected * dy / cp_distance # offset for arrow wedge dx = dx / cp_distance * head_dist dy = dy / cp_distance * head_dist dx1, dy1 = cos_t * dx + sin_t * dy, -sin_t * dx + cos_t * dy dx2, dy2 = cos_t * dx - sin_t * dy, sin_t * dx + cos_t * dy vertices_arrow = [(x1 + ddx + dx1, y1 + ddy + dy1), (x1 + ddx, y1 + ddy), (x1 + ddx + dx2, y1 + ddy + dy2)] codes_arrow = [Path.MOVETO, Path.LINETO, Path.LINETO] return vertices_arrow, codes_arrow, ddx, ddy def transmute(self, path, mutation_size, linewidth): head_length = self.head_length * mutation_size head_width = self.head_width * mutation_size head_dist = math.sqrt(head_length ** 2 + head_width ** 2) cos_t, sin_t = head_length / head_dist, head_width / head_dist # begin arrow x0, y0 = path.vertices[0] x1, y1 = path.vertices[1] # If there is no room for an arrow and a line, then skip the arrow has_begin_arrow = self.beginarrow and not (x0 == x1 and y0 == y1) if has_begin_arrow: verticesA, codesA, ddxA, ddyA = \ self._get_arrow_wedge(x1, y1, x0, y0, head_dist, cos_t, sin_t, linewidth) else: verticesA, codesA = [], [] ddxA, ddyA = 0., 0. # end arrow x2, y2 = path.vertices[-2] x3, y3 = path.vertices[-1] # If there is no room for an arrow and a line, then skip the arrow has_end_arrow = (self.endarrow and not ((x2 == x3) and (y2 == y3))) if has_end_arrow: verticesB, codesB, ddxB, ddyB = \ self._get_arrow_wedge(x2, y2, x3, y3, head_dist, cos_t, sin_t, linewidth) else: verticesB, codesB = [], [] ddxB, ddyB = 0., 0. # this simple code will not work if ddx, ddy is greater than # separation bettern vertices. _path = [Path(np.concatenate([[(x0 + ddxA, y0 + ddyA)], path.vertices[1:-1], [(x3 + ddxB, y3 + ddyB)]]), path.codes)] _fillable = [False] if has_begin_arrow: if self.fillbegin: p = np.concatenate([verticesA, [verticesA[0], verticesA[0]], ]) c = np.concatenate([codesA, [Path.LINETO, Path.CLOSEPOLY]]) _path.append(Path(p, c)) _fillable.append(True) else: _path.append(Path(verticesA, codesA)) _fillable.append(False) if has_end_arrow: if self.fillend: _fillable.append(True) p = np.concatenate([verticesB, [verticesB[0], verticesB[0]], ]) c = np.concatenate([codesB, [Path.LINETO, Path.CLOSEPOLY]]) _path.append(Path(p, c)) else: _fillable.append(False) _path.append(Path(verticesB, codesB)) return _path, _fillable class Curve(_Curve): """ A simple curve without any arrow head. """ def __init__(self): super(ArrowStyle.Curve, self).__init__( beginarrow=False, endarrow=False) _style_list["-"] = Curve class CurveA(_Curve): """ An arrow with a head at its begin point. """ def __init__(self, head_length=.4, head_width=.2): """ Parameters ---------- head_length : float, optional, default : 0.4 Length of the arrow head head_width : float, optional, default : 0.2 Width of the arrow head """ super(ArrowStyle.CurveA, self).__init__( beginarrow=True, endarrow=False, head_length=head_length, head_width=head_width) _style_list["<-"] = CurveA class CurveB(_Curve): """ An arrow with a head at its end point. """ def __init__(self, head_length=.4, head_width=.2): """ Parameters ---------- head_length : float, optional, default : 0.4 Length of the arrow head head_width : float, optional, default : 0.2 Width of the arrow head """ super(ArrowStyle.CurveB, self).__init__( beginarrow=False, endarrow=True, head_length=head_length, head_width=head_width) _style_list["->"] = CurveB class CurveAB(_Curve): """ An arrow with heads both at the begin and the end point. """ def __init__(self, head_length=.4, head_width=.2): """ Parameters ---------- head_length : float, optional, default : 0.4 Length of the arrow head head_width : float, optional, default : 0.2 Width of the arrow head """ super(ArrowStyle.CurveAB, self).__init__( beginarrow=True, endarrow=True, head_length=head_length, head_width=head_width) _style_list["<->"] = CurveAB class CurveFilledA(_Curve): """ An arrow with filled triangle head at the begin. """ def __init__(self, head_length=.4, head_width=.2): """ Parameters ---------- head_length : float, optional, default : 0.4 Length of the arrow head head_width : float, optional, default : 0.2 Width of the arrow head """ super(ArrowStyle.CurveFilledA, self).__init__( beginarrow=True, endarrow=False, fillbegin=True, fillend=False, head_length=head_length, head_width=head_width) _style_list["<|-"] = CurveFilledA class CurveFilledB(_Curve): """ An arrow with filled triangle head at the end. """ def __init__(self, head_length=.4, head_width=.2): """ Parameters ---------- head_length : float, optional, default : 0.4 Length of the arrow head head_width : float, optional, default : 0.2 Width of the arrow head """ super(ArrowStyle.CurveFilledB, self).__init__( beginarrow=False, endarrow=True, fillbegin=False, fillend=True, head_length=head_length, head_width=head_width) _style_list["-|>"] = CurveFilledB class CurveFilledAB(_Curve): """ An arrow with filled triangle heads at both ends. """ def __init__(self, head_length=.4, head_width=.2): """ Parameters ---------- head_length : float, optional, default : 0.4 Length of the arrow head head_width : float, optional, default : 0.2 Width of the arrow head """ super(ArrowStyle.CurveFilledAB, self).__init__( beginarrow=True, endarrow=True, fillbegin=True, fillend=True, head_length=head_length, head_width=head_width) _style_list["<|-|>"] = CurveFilledAB class _Bracket(_Base): def __init__(self, bracketA=None, bracketB=None, widthA=1., widthB=1., lengthA=0.2, lengthB=0.2, angleA=None, angleB=None, scaleA=None, scaleB=None): self.bracketA, self.bracketB = bracketA, bracketB self.widthA, self.widthB = widthA, widthB self.lengthA, self.lengthB = lengthA, lengthB self.angleA, self.angleB = angleA, angleB self.scaleA, self.scaleB = scaleA, scaleB def _get_bracket(self, x0, y0, cos_t, sin_t, width, length): # arrow from x0, y0 to x1, y1 from matplotlib.bezier import get_normal_points x1, y1, x2, y2 = get_normal_points(x0, y0, cos_t, sin_t, width) dx, dy = length * cos_t, length * sin_t vertices_arrow = [(x1 + dx, y1 + dy), (x1, y1), (x2, y2), (x2 + dx, y2 + dy)] codes_arrow = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO] return vertices_arrow, codes_arrow def transmute(self, path, mutation_size, linewidth): if self.scaleA is None: scaleA = mutation_size else: scaleA = self.scaleA if self.scaleB is None: scaleB = mutation_size else: scaleB = self.scaleB vertices_list, codes_list = [], [] if self.bracketA: x0, y0 = path.vertices[0] x1, y1 = path.vertices[1] cos_t, sin_t = get_cos_sin(x1, y1, x0, y0) verticesA, codesA = self._get_bracket(x0, y0, cos_t, sin_t, self.widthA * scaleA, self.lengthA * scaleA) vertices_list.append(verticesA) codes_list.append(codesA) vertices_list.append(path.vertices) codes_list.append(path.codes) if self.bracketB: x0, y0 = path.vertices[-1] x1, y1 = path.vertices[-2] cos_t, sin_t = get_cos_sin(x1, y1, x0, y0) verticesB, codesB = self._get_bracket(x0, y0, cos_t, sin_t, self.widthB * scaleB, self.lengthB * scaleB) vertices_list.append(verticesB) codes_list.append(codesB) vertices = np.concatenate(vertices_list) codes = np.concatenate(codes_list) p = Path(vertices, codes) return p, False class BracketAB(_Bracket): """ An arrow with a bracket(]) at both ends. """ def __init__(self, widthA=1., lengthA=0.2, angleA=None, widthB=1., lengthB=0.2, angleB=None): """ Parameters ---------- widthA : float, optional, default : 1.0 Width of the bracket lengthA : float, optional, default : 0.2 Length of the bracket angleA : float, optional, default : None Angle between the bracket and the line widthB : float, optional, default : 1.0 Width of the bracket lengthB : float, optional, default : 0.2 Length of the bracket angleB : float, optional, default : None Angle between the bracket and the line """ super(ArrowStyle.BracketAB, self).__init__( True, True, widthA=widthA, lengthA=lengthA, angleA=angleA, widthB=widthB, lengthB=lengthB, angleB=angleB) _style_list["]-["] = BracketAB class BracketA(_Bracket): """ An arrow with a bracket(]) at its end. """ def __init__(self, widthA=1., lengthA=0.2, angleA=None): """ Parameters ---------- widthA : float, optional, default : 1.0 Width of the bracket lengthA : float, optional, default : 0.2 Length of the bracket angleA : float, optional, default : None Angle between the bracket and the line """ super(ArrowStyle.BracketA, self).__init__(True, None, widthA=widthA, lengthA=lengthA, angleA=angleA) _style_list["]-"] = BracketA class BracketB(_Bracket): """ An arrow with a bracket([) at its end. """ def __init__(self, widthB=1., lengthB=0.2, angleB=None): """ Parameters ---------- widthB : float, optional, default : 1.0 Width of the bracket lengthB : float, optional, default : 0.2 Length of the bracket angleB : float, optional, default : None Angle between the bracket and the line """ super(ArrowStyle.BracketB, self).__init__(None, True, widthB=widthB, lengthB=lengthB, angleB=angleB) _style_list["-["] = BracketB class BarAB(_Bracket): """ An arrow with a bar(|) at both ends. """ def __init__(self, widthA=1., angleA=None, widthB=1., angleB=None): """ Parameters ---------- widthA : float, optional, default : 1.0 Width of the bracket angleA : float, optional, default : None Angle between the bracket and the line widthB : float, optional, default : 1.0 Width of the bracket angleB : float, optional, default : None Angle between the bracket and the line """ super(ArrowStyle.BarAB, self).__init__( True, True, widthA=widthA, lengthA=0, angleA=angleA, widthB=widthB, lengthB=0, angleB=angleB) _style_list["|-|"] = BarAB class Simple(_Base): """ A simple arrow. Only works with a quadratic bezier curve. """ def __init__(self, head_length=.5, head_width=.5, tail_width=.2): """ Parameters ---------- head_length : float, optional, default : 0.5 Length of the arrow head head_width : float, optional, default : 0.5 Width of the arrow head tail_width : float, optional, default : 0.2 Width of the arrow tail """ self.head_length, self.head_width, self.tail_width = \ head_length, head_width, tail_width super(ArrowStyle.Simple, self).__init__() def transmute(self, path, mutation_size, linewidth): x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path) # divide the path into a head and a tail head_length = self.head_length * mutation_size in_f = inside_circle(x2, y2, head_length) arrow_path = [(x0, y0), (x1, y1), (x2, y2)] from .bezier import NonIntersectingPathException try: arrow_out, arrow_in = \ split_bezier_intersecting_with_closedpath(arrow_path, in_f, tolerence=0.01) except NonIntersectingPathException: # if this happens, make a straight line of the head_length # long. x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length) x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2) arrow_in = [(x0, y0), (x1n, y1n), (x2, y2)] arrow_out = None # head head_width = self.head_width * mutation_size head_left, head_right = make_wedged_bezier2(arrow_in, head_width / 2., wm=.5) # tail if arrow_out is not None: tail_width = self.tail_width * mutation_size tail_left, tail_right = get_parallels(arrow_out, tail_width / 2.) patch_path = [(Path.MOVETO, tail_right[0]), (Path.CURVE3, tail_right[1]), (Path.CURVE3, tail_right[2]), (Path.LINETO, head_right[0]), (Path.CURVE3, head_right[1]), (Path.CURVE3, head_right[2]), (Path.CURVE3, head_left[1]), (Path.CURVE3, head_left[0]), (Path.LINETO, tail_left[2]), (Path.CURVE3, tail_left[1]), (Path.CURVE3, tail_left[0]), (Path.LINETO, tail_right[0]), (Path.CLOSEPOLY, tail_right[0]), ] else: patch_path = [(Path.MOVETO, head_right[0]), (Path.CURVE3, head_right[1]), (Path.CURVE3, head_right[2]), (Path.CURVE3, head_left[1]), (Path.CURVE3, head_left[0]), (Path.CLOSEPOLY, head_left[0]), ] path = Path([p for c, p in patch_path], [c for c, p in patch_path]) return path, True _style_list["simple"] = Simple class Fancy(_Base): """ A fancy arrow. Only works with a quadratic bezier curve. """ def __init__(self, head_length=.4, head_width=.4, tail_width=.4): """ Parameters ---------- head_length : float, optional, default : 0.4 Length of the arrow head head_width : float, optional, default : 0.4 Width of the arrow head tail_width : float, optional, default : 0.4 Width of the arrow tail """ self.head_length, self.head_width, self.tail_width = \ head_length, head_width, tail_width super(ArrowStyle.Fancy, self).__init__() def transmute(self, path, mutation_size, linewidth): x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path) # divide the path into a head and a tail head_length = self.head_length * mutation_size arrow_path = [(x0, y0), (x1, y1), (x2, y2)] from .bezier import NonIntersectingPathException # path for head in_f = inside_circle(x2, y2, head_length) try: path_out, path_in = \ split_bezier_intersecting_with_closedpath( arrow_path, in_f, tolerence=0.01) except NonIntersectingPathException: # if this happens, make a straight line of the head_length # long. x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length) x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2) arrow_path = [(x0, y0), (x1n, y1n), (x2, y2)] path_head = arrow_path else: path_head = path_in # path for head in_f = inside_circle(x2, y2, head_length * .8) path_out, path_in = split_bezier_intersecting_with_closedpath( arrow_path, in_f, tolerence=0.01 ) path_tail = path_out # head head_width = self.head_width * mutation_size head_l, head_r = make_wedged_bezier2(path_head, head_width / 2., wm=.6) # tail tail_width = self.tail_width * mutation_size tail_left, tail_right = make_wedged_bezier2(path_tail, tail_width * .5, w1=1., wm=0.6, w2=0.3) # path for head in_f = inside_circle(x0, y0, tail_width * .3) path_in, path_out = split_bezier_intersecting_with_closedpath( arrow_path, in_f, tolerence=0.01 ) tail_start = path_in[-1] head_right, head_left = head_r, head_l patch_path = [(Path.MOVETO, tail_start), (Path.LINETO, tail_right[0]), (Path.CURVE3, tail_right[1]), (Path.CURVE3, tail_right[2]), (Path.LINETO, head_right[0]), (Path.CURVE3, head_right[1]), (Path.CURVE3, head_right[2]), (Path.CURVE3, head_left[1]), (Path.CURVE3, head_left[0]), (Path.LINETO, tail_left[2]), (Path.CURVE3, tail_left[1]), (Path.CURVE3, tail_left[0]), (Path.LINETO, tail_start), (Path.CLOSEPOLY, tail_start), ] path = Path([p for c, p in patch_path], [c for c, p in patch_path]) return path, True _style_list["fancy"] = Fancy class Wedge(_Base): """ Wedge(?) shape. Only works with a quadratic bezier curve. The begin point has a width of the tail_width and the end point has a width of 0. At the middle, the width is shrink_factor*tail_width. """ def __init__(self, tail_width=.3, shrink_factor=0.5): """ Parameters ---------- tail_width : float, optional, default : 0.3 Width of the tail shrink_factor : float, optional, default : 0.5 Fraction of the arrow width at the middle point """ self.tail_width = tail_width self.shrink_factor = shrink_factor super(ArrowStyle.Wedge, self).__init__() def transmute(self, path, mutation_size, linewidth): x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path) arrow_path = [(x0, y0), (x1, y1), (x2, y2)] b_plus, b_minus = make_wedged_bezier2( arrow_path, self.tail_width * mutation_size / 2., wm=self.shrink_factor) patch_path = [(Path.MOVETO, b_plus[0]), (Path.CURVE3, b_plus[1]), (Path.CURVE3, b_plus[2]), (Path.LINETO, b_minus[2]), (Path.CURVE3, b_minus[1]), (Path.CURVE3, b_minus[0]), (Path.CLOSEPOLY, b_minus[0]), ] path = Path([p for c, p in patch_path], [c for c, p in patch_path]) return path, True _style_list["wedge"] = Wedge if __doc__: __doc__ = cbook.dedent(__doc__) % \ {"AvailableArrowstyles": _pprint_styles(_style_list)} docstring.interpd.update( AvailableArrowstyles=_pprint_styles(ArrowStyle._style_list), AvailableConnectorstyles=_pprint_styles(ConnectionStyle._style_list), ) class FancyArrowPatch(Patch): """ A fancy arrow patch. It draws an arrow using the :class:`ArrowStyle`. The head and tail positions are fixed at the specified start and end points of the arrow, but the size and shape (in display coordinates) of the arrow does not change when the axis is moved or zoomed. """ _edge_default = True def __str__(self): if self._posA_posB is not None: (x1, y1), (x2, y2) = self._posA_posB return self.__class__.__name__ \ + "(%g,%g->%g,%g)" % (x1, y1, x2, y2) else: return self.__class__.__name__ \ + "(%s)" % (str(self._path_original),) @docstring.dedent_interpd def __init__(self, posA=None, posB=None, path=None, arrowstyle="simple", arrow_transmuter=None, connectionstyle="arc3", connector=None, patchA=None, patchB=None, shrinkA=2, shrinkB=2, mutation_scale=1, mutation_aspect=None, dpi_cor=1, **kwargs): """ If *posA* and *posB* are given, a path connecting two points is created according to *connectionstyle*. The path will be clipped with *patchA* and *patchB* and further shrunken by *shrinkA* and *shrinkB*. An arrow is drawn along this resulting path using the *arrowstyle* parameter. Alternatively if *path* is provided, an arrow is drawn along this path and *patchA*, *patchB*, *shrinkA*, and *shrinkB* are ignored. Parameters ---------- posA, posB : None, tuple, optional (default: None) (x,y) coordinates of arrow tail and arrow head respectively. path : None, Path (default: None) :class:`matplotlib.path.Path` instance. If provided, an arrow is drawn along this path and *patchA*, *patchB*, *shrinkA*, and *shrinkB* are ignored. arrowstyle : str or ArrowStyle, optional (default: 'simple') Describes how the fancy arrow will be drawn. It can be string of the available arrowstyle names, with optional comma-separated attributes, or an :class:`ArrowStyle` instance. The optional attributes are meant to be scaled with the *mutation_scale*. The following arrow styles are available: %(AvailableArrowstyles)s arrow_transmuter : Ignored connectionstyle : str, ConnectionStyle, or None, optional (default: 'arc3') Describes how *posA* and *posB* are connected. It can be an instance of the :class:`ConnectionStyle` class or a string of the connectionstyle name, with optional comma-separated attributes. The following connection styles are available: %(AvailableConnectorstyles)s connector : Ignored patchA, patchB : None, Patch, optional (default: None) Head and tail patch respectively. :class:`matplotlib.patch.Patch` instance. shrinkA, shrinkB : scalar, optional (default: 2) Shrinking factor of the tail and head of the arrow respectively mutation_scale : scalar, optional (default: 1) Value with which attributes of *arrowstyle* (e.g., *head_length*) will be scaled. mutation_aspect : None, scalar, optional (default: None) The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. dpi_cor : scalar, optional (default: 1) dpi_cor is currently used for linewidth-related things and shrink factor. Mutation scale is affected by this. Notes ----- Valid kwargs are: %(Patch)s """ Patch.__init__(self, **kwargs) if posA is not None and posB is not None and path is None: self._posA_posB = [posA, posB] if connectionstyle is None: connectionstyle = "arc3" self.set_connectionstyle(connectionstyle) elif posA is None and posB is None and path is not None: self._posA_posB = None self._connetors = None else: raise ValueError("either posA and posB, or path need to provided") self.patchA = patchA self.patchB = patchB self.shrinkA = shrinkA self.shrinkB = shrinkB self._path_original = path self.set_arrowstyle(arrowstyle) self._mutation_scale = mutation_scale self._mutation_aspect = mutation_aspect self.set_dpi_cor(dpi_cor) def set_dpi_cor(self, dpi_cor): """ dpi_cor is currently used for linewidth-related things and shrink factor. Mutation scale is affected by this. Parameters ---------- dpi_cor : scalar """ self._dpi_cor = dpi_cor self.stale = True def get_dpi_cor(self): """ dpi_cor is currently used for linewidth-related things and shrink factor. Mutation scale is affected by this. Returns ------- dpi_cor : scalar """ return self._dpi_cor def set_positions(self, posA, posB): """ Set the begin and end positions of the connecting path. Parameters ---------- posA, posB : None, tuple (x,y) coordinates of arrow tail and arrow head respectively. If `None` use current value. """ if posA is not None: self._posA_posB[0] = posA if posB is not None: self._posA_posB[1] = posB self.stale = True def set_patchA(self, patchA): """ Set the tail patch. Parameters ---------- patchA : Patch :class:`matplotlib.patch.Patch` instance. """ self.patchA = patchA self.stale = True def set_patchB(self, patchB): """ Set the head patch. Parameters ---------- patchB : Patch :class:`matplotlib.patch.Patch` instance. """ self.patchB = patchB self.stale = True def set_connectionstyle(self, connectionstyle, **kw): """ Set the connection style. Old attributes are forgotten. Parameters ---------- connectionstyle : None, ConnectionStyle instance, or string Can be a string with connectionstyle name with optional comma-separated attributes, e.g.:: set_connectionstyle("arc,angleA=0,armA=30,rad=10") Alternatively, the attributes can be provided as keywords, e.g.:: set_connectionstyle("arc", angleA=0,armA=30,rad=10) Without any arguments (or with ``connectionstyle=None``), return available styles as a list of strings. """ if connectionstyle is None: return ConnectionStyle.pprint_styles() if (isinstance(connectionstyle, ConnectionStyle._Base) or callable(connectionstyle)): self._connector = connectionstyle else: self._connector = ConnectionStyle(connectionstyle, **kw) self.stale = True def get_connectionstyle(self): """ Return the :class:`ConnectionStyle` instance. """ return self._connector def set_arrowstyle(self, arrowstyle=None, **kw): """ Set the arrow style. Old attributes are forgotten. Without arguments (or with ``arrowstyle=None``) returns available box styles as a list of strings. Parameters ---------- arrowstyle : None, ArrowStyle, str, optional (default: None) Can be a string with arrowstyle name with optional comma-separated attributes, e.g.:: set_arrowstyle("Fancy,head_length=0.2") Alternatively attributes can be provided as keywords, e.g.:: set_arrowstyle("fancy", head_length=0.2) """ if arrowstyle is None: return ArrowStyle.pprint_styles() if isinstance(arrowstyle, ArrowStyle._Base): self._arrow_transmuter = arrowstyle else: self._arrow_transmuter = ArrowStyle(arrowstyle, **kw) self.stale = True def get_arrowstyle(self): """ Return the arrowstyle object. """ return self._arrow_transmuter def set_mutation_scale(self, scale): """ Set the mutation scale. Parameters ---------- scale : scalar """ self._mutation_scale = scale self.stale = True def get_mutation_scale(self): """ Return the mutation scale. Returns ------- scale : scalar """ return self._mutation_scale def set_mutation_aspect(self, aspect): """ Set the aspect ratio of the bbox mutation. Parameters ---------- aspect : scalar """ self._mutation_aspect = aspect self.stale = True def get_mutation_aspect(self): """ Return the aspect ratio of the bbox mutation. """ return self._mutation_aspect def get_path(self): """ Return the path of the arrow in the data coordinates. Use get_path_in_displaycoord() method to retrieve the arrow path in display coordinates. """ _path, fillable = self.get_path_in_displaycoord() if cbook.iterable(fillable): _path = concatenate_paths(_path) return self.get_transform().inverted().transform_path(_path) def get_path_in_displaycoord(self): """ Return the mutated path of the arrow in display coordinates. """ dpi_cor = self.get_dpi_cor() if self._posA_posB is not None: posA = self.get_transform().transform_point(self._posA_posB[0]) posB = self.get_transform().transform_point(self._posA_posB[1]) _path = self.get_connectionstyle()(posA, posB, patchA=self.patchA, patchB=self.patchB, shrinkA=self.shrinkA * dpi_cor, shrinkB=self.shrinkB * dpi_cor ) else: _path = self.get_transform().transform_path(self._path_original) _path, fillable = self.get_arrowstyle()( _path, self.get_mutation_scale() * dpi_cor, self.get_linewidth() * dpi_cor, self.get_mutation_aspect()) # if not fillable: # self._fill = False return _path, fillable def draw(self, renderer): if not self.get_visible(): return renderer.open_group('patch', self.get_gid()) gc = renderer.new_gc() gc.set_foreground(self._edgecolor, isRGBA=True) lw = self._linewidth if self._edgecolor[3] == 0: lw = 0 gc.set_linewidth(lw) gc.set_dashes(self._dashoffset, self._dashes) gc.set_antialiased(self._antialiased) self._set_gc_clip(gc) gc.set_capstyle('round') gc.set_snap(self.get_snap()) rgbFace = self._facecolor if rgbFace[3] == 0: rgbFace = None # (some?) renderers expect this as no-fill signal gc.set_alpha(self._alpha) if self._hatch: gc.set_hatch(self._hatch) if self._hatch_color is not None: try: gc.set_hatch_color(self._hatch_color) except AttributeError: # if we end up with a GC that does not have this method warnings.warn("Your backend does not support setting the " "hatch color.") if self.get_sketch_params() is not None: gc.set_sketch_params(*self.get_sketch_params()) # FIXME : dpi_cor is for the dpi-dependecy of the # linewidth. There could be room for improvement. # # dpi_cor = renderer.points_to_pixels(1.) self.set_dpi_cor(renderer.points_to_pixels(1.)) path, fillable = self.get_path_in_displaycoord() if not cbook.iterable(fillable): path = [path] fillable = [fillable] affine = transforms.IdentityTransform() if self.get_path_effects(): from matplotlib.patheffects import PathEffectRenderer renderer = PathEffectRenderer(self.get_path_effects(), renderer) for p, f in zip(path, fillable): if f: renderer.draw_path(gc, p, affine, rgbFace) else: renderer.draw_path(gc, p, affine, None) gc.restore() renderer.close_group('patch') self.stale = False class ConnectionPatch(FancyArrowPatch): """ A :class:`~matplotlib.patches.ConnectionPatch` class is to make connecting lines between two points (possibly in different axes). """ def __str__(self): return "ConnectionPatch((%g,%g),(%g,%g))" % \ (self.xy1[0], self.xy1[1], self.xy2[0], self.xy2[1]) @docstring.dedent_interpd def __init__(self, xyA, xyB, coordsA, coordsB=None, axesA=None, axesB=None, arrowstyle="-", arrow_transmuter=None, connectionstyle="arc3", connector=None, patchA=None, patchB=None, shrinkA=0., shrinkB=0., mutation_scale=10., mutation_aspect=None, clip_on=False, dpi_cor=1., **kwargs): """ Connect point *xyA* in *coordsA* with point *xyB* in *coordsB* Valid keys are =============== ====================================================== Key Description =============== ====================================================== arrowstyle the arrow style connectionstyle the connection style relpos default is (0.5, 0.5) patchA default is bounding box of the text patchB default is None shrinkA default is 2 points shrinkB default is 2 points mutation_scale default is text size (in points) mutation_aspect default is 1. ? any key for :class:`matplotlib.patches.PathPatch` =============== ====================================================== *coordsA* and *coordsB* are strings that indicate the coordinates of *xyA* and *xyB*. ================= =================================================== Property Description ================= =================================================== 'figure points' points from the lower left corner of the figure 'figure pixels' pixels from the lower left corner of the figure 'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right 'axes points' points from lower left corner of axes 'axes pixels' pixels from lower left corner of axes 'axes fraction' 0,1 is lower left of axes and 1,1 is upper right 'data' use the coordinate system of the object being annotated (default) 'offset points' Specify an offset (in points) from the *xy* value 'polar' you can specify *theta*, *r* for the annotation, even in cartesian plots. Note that if you are using a polar axes, you do not need to specify polar for the coordinate system since that is the native "data" coordinate system. ================= =================================================== """ if coordsB is None: coordsB = coordsA # we'll draw ourself after the artist we annotate by default self.xy1 = xyA self.xy2 = xyB self.coords1 = coordsA self.coords2 = coordsB self.axesA = axesA self.axesB = axesB FancyArrowPatch.__init__(self, posA=(0, 0), posB=(1, 1), arrowstyle=arrowstyle, arrow_transmuter=arrow_transmuter, connectionstyle=connectionstyle, connector=connector, patchA=patchA, patchB=patchB, shrinkA=shrinkA, shrinkB=shrinkB, mutation_scale=mutation_scale, mutation_aspect=mutation_aspect, clip_on=clip_on, dpi_cor=dpi_cor, **kwargs) # if True, draw annotation only if self.xy is inside the axes self._annotation_clip = None def _get_xy(self, x, y, s, axes=None): """ calculate the pixel position of given point """ if axes is None: axes = self.axes if s == 'data': trans = axes.transData x = float(self.convert_xunits(x)) y = float(self.convert_yunits(y)) return trans.transform_point((x, y)) elif s == 'offset points': # convert the data point dx, dy = self.xy # prevent recursion if self.xycoords == 'offset points': return self._get_xy(dx, dy, 'data') dx, dy = self._get_xy(dx, dy, self.xycoords) # convert the offset dpi = self.figure.get_dpi() x *= dpi / 72. y *= dpi / 72. # add the offset to the data point x += dx y += dy return x, y elif s == 'polar': theta, r = x, y x = r * np.cos(theta) y = r * np.sin(theta) trans = axes.transData return trans.transform_point((x, y)) elif s == 'figure points': # points from the lower left corner of the figure dpi = self.figure.dpi l, b, w, h = self.figure.bbox.bounds r = l + w t = b + h x *= dpi / 72. y *= dpi / 72. if x < 0: x = r + x if y < 0: y = t + y return x, y elif s == 'figure pixels': # pixels from the lower left corner of the figure l, b, w, h = self.figure.bbox.bounds r = l + w t = b + h if x < 0: x = r + x if y < 0: y = t + y return x, y elif s == 'figure fraction': # (0,0) is lower left, (1,1) is upper right of figure trans = self.figure.transFigure return trans.transform_point((x, y)) elif s == 'axes points': # points from the lower left corner of the axes dpi = self.figure.dpi l, b, w, h = axes.bbox.bounds r = l + w t = b + h if x < 0: x = r + x * dpi / 72. else: x = l + x * dpi / 72. if y < 0: y = t + y * dpi / 72. else: y = b + y * dpi / 72. return x, y elif s == 'axes pixels': #pixels from the lower left corner of the axes l, b, w, h = axes.bbox.bounds r = l + w t = b + h if x < 0: x = r + x else: x = l + x if y < 0: y = t + y else: y = b + y return x, y elif s == 'axes fraction': #(0,0) is lower left, (1,1) is upper right of axes trans = axes.transAxes return trans.transform_point((x, y)) def set_annotation_clip(self, b): """ set *annotation_clip* attribute. * True: the annotation will only be drawn when self.xy is inside the axes. * False: the annotation will always be drawn regardless of its position. * None: the self.xy will be checked only if *xycoords* is "data" """ self._annotation_clip = b self.stale = True def get_annotation_clip(self): """ Return *annotation_clip* attribute. See :meth:`set_annotation_clip` for the meaning of return values. """ return self._annotation_clip def get_path_in_displaycoord(self): """ Return the mutated path of the arrow in the display coord """ dpi_cor = self.get_dpi_cor() x, y = self.xy1 posA = self._get_xy(x, y, self.coords1, self.axesA) x, y = self.xy2 posB = self._get_xy(x, y, self.coords2, self.axesB) _path = self.get_connectionstyle()(posA, posB, patchA=self.patchA, patchB=self.patchB, shrinkA=self.shrinkA * dpi_cor, shrinkB=self.shrinkB * dpi_cor ) _path, fillable = self.get_arrowstyle()( _path, self.get_mutation_scale() * dpi_cor, self.get_linewidth() * dpi_cor, self.get_mutation_aspect() ) return _path, fillable def _check_xy(self, renderer): """ check if the annotation need to be drawn. """ b = self.get_annotation_clip() if b or (b is None and self.coords1 == "data"): x, y = self.xy1 xy_pixel = self._get_xy(x, y, self.coords1, self.axesA) if not self.axes.contains_point(xy_pixel): return False if b or (b is None and self.coords2 == "data"): x, y = self.xy2 xy_pixel = self._get_xy(x, y, self.coords2, self.axesB) if self.axesB is None: axes = self.axes else: axes = self.axesB if not axes.contains_point(xy_pixel): return False return True def draw(self, renderer): """ Draw. """ if renderer is not None: self._renderer = renderer if not self.get_visible(): return if not self._check_xy(renderer): return FancyArrowPatch.draw(self, renderer)
153,118
31.433595
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tight_bbox.py
""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(fig, bbox_inches, fixed_dpi) return bbox_inches, r
2,585
28.386364
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/ticker.py
""" Tick locating and formatting ============================ This module contains classes to support completely configurable tick locating and formatting. Although the locators know nothing about major or minor ticks, they are used by the Axis class to support major and minor tick locating and formatting. Generic tick locators and formatters are provided, as well as domain specific custom ones. Default Formatter ----------------- The default formatter identifies when the x-data being plotted is a small range on top of a large off set. To reduce the chances that the ticklabels overlap the ticks are labeled as deltas from a fixed offset. For example:: ax.plot(np.arange(2000, 2010), range(10)) will have tick of 0-9 with an offset of +2e3. If this is not desired turn off the use of the offset on the default formatter:: ax.get_xaxis().get_major_formatter().set_useOffset(False) set the rcParam ``axes.formatter.useoffset=False`` to turn it off globally, or set a different formatter. Tick locating ------------- The Locator class is the base class for all tick locators. The locators handle autoscaling of the view limits based on the data limits, and the choosing of tick locations. A useful semi-automatic tick locator is `MultipleLocator`. It is initialized with a base, e.g., 10, and it picks axis limits and ticks that are multiples of that base. The Locator subclasses defined here are :class:`AutoLocator` `MaxNLocator` with simple defaults. This is the default tick locator for most plotting. :class:`MaxNLocator` Finds up to a max number of intervals with ticks at nice locations. :class:`LinearLocator` Space ticks evenly from min to max. :class:`LogLocator` Space ticks logarithmically from min to max. :class:`MultipleLocator` Ticks and range are a multiple of base; either integer or float. :class:`FixedLocator` Tick locations are fixed. :class:`IndexLocator` Locator for index plots (e.g., where ``x = range(len(y))``). :class:`NullLocator` No ticks. :class:`SymmetricalLogLocator` Locator for use with with the symlog norm; works like `LogLocator` for the part outside of the threshold and adds 0 if inside the limits. :class:`LogitLocator` Locator for logit scaling. :class:`OldAutoLocator` Choose a `MultipleLocator` and dynamically reassign it for intelligent ticking during navigation. :class:`AutoMinorLocator` Locator for minor ticks when the axis is linear and the major ticks are uniformly spaced. Subdivides the major tick interval into a specified number of minor intervals, defaulting to 4 or 5 depending on the major interval. There are a number of locators specialized for date locations - see the `dates` module. You can define your own locator by deriving from Locator. You must override the ``__call__`` method, which returns a sequence of locations, and you will probably want to override the autoscale method to set the view limits from the data limits. If you want to override the default locator, use one of the above or a custom locator and pass it to the x or y axis instance. The relevant methods are:: ax.xaxis.set_major_locator(xmajor_locator) ax.xaxis.set_minor_locator(xminor_locator) ax.yaxis.set_major_locator(ymajor_locator) ax.yaxis.set_minor_locator(yminor_locator) The default minor locator is `NullLocator`, i.e., no minor ticks on by default. Tick formatting --------------- Tick formatting is controlled by classes derived from Formatter. The formatter operates on a single tick value and returns a string to the axis. :class:`NullFormatter` No labels on the ticks. :class:`IndexFormatter` Set the strings from a list of labels. :class:`FixedFormatter` Set the strings manually for the labels. :class:`FuncFormatter` User defined function sets the labels. :class:`StrMethodFormatter` Use string `format` method. :class:`FormatStrFormatter` Use an old-style sprintf format string. :class:`ScalarFormatter` Default formatter for scalars: autopick the format string. :class:`LogFormatter` Formatter for log axes. :class:`LogFormatterExponent` Format values for log axis using ``exponent = log_base(value)``. :class:`LogFormatterMathtext` Format values for log axis using ``exponent = log_base(value)`` using Math text. :class:`LogFormatterSciNotation` Format values for log axis using scientific notation. :class:`LogitFormatter` Probability formatter. :class:`EngFormatter` Format labels in engineering notation :class:`PercentFormatter` Format labels as a percentage You can derive your own formatter from the Formatter base class by simply overriding the ``__call__`` method. The formatter class has access to the axis view and data limits. To control the major and minor tick label formats, use one of the following methods:: ax.xaxis.set_major_formatter(xmajor_formatter) ax.xaxis.set_minor_formatter(xminor_formatter) ax.yaxis.set_major_formatter(ymajor_formatter) ax.yaxis.set_minor_formatter(yminor_formatter) See :ref:`sphx_glr_gallery_ticks_and_spines_major_minor_demo.py` for an example of setting major and minor ticks. See the :mod:`matplotlib.dates` module for more information and examples of using date locators and formatters. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import itertools import locale import math import numpy as np from matplotlib import rcParams from matplotlib import cbook from matplotlib import transforms as mtransforms from matplotlib.cbook import mplDeprecation import warnings __all__ = ('TickHelper', 'Formatter', 'FixedFormatter', 'NullFormatter', 'FuncFormatter', 'FormatStrFormatter', 'StrMethodFormatter', 'ScalarFormatter', 'LogFormatter', 'LogFormatterExponent', 'LogFormatterMathtext', 'IndexFormatter', 'LogFormatterSciNotation', 'LogitFormatter', 'EngFormatter', 'PercentFormatter', 'Locator', 'IndexLocator', 'FixedLocator', 'NullLocator', 'LinearLocator', 'LogLocator', 'AutoLocator', 'MultipleLocator', 'MaxNLocator', 'AutoMinorLocator', 'SymmetricalLogLocator', 'LogitLocator') if six.PY3: long = int # Work around numpy/numpy#6127. def _divmod(x, y): if isinstance(x, np.generic): x = x.item() if isinstance(y, np.generic): y = y.item() return six.moves.builtins.divmod(x, y) def _mathdefault(s): return '\\mathdefault{%s}' % s class _DummyAxis(object): def __init__(self, minpos=0): self.dataLim = mtransforms.Bbox.unit() self.viewLim = mtransforms.Bbox.unit() self._minpos = minpos def get_view_interval(self): return self.viewLim.intervalx def set_view_interval(self, vmin, vmax): self.viewLim.intervalx = vmin, vmax def get_minpos(self): return self._minpos def get_data_interval(self): return self.dataLim.intervalx def set_data_interval(self, vmin, vmax): self.dataLim.intervalx = vmin, vmax def get_tick_space(self): # Just use the long-standing default of nbins==9 return 9 class TickHelper(object): axis = None def set_axis(self, axis): self.axis = axis def create_dummy_axis(self, **kwargs): if self.axis is None: self.axis = _DummyAxis(**kwargs) def set_view_interval(self, vmin, vmax): self.axis.set_view_interval(vmin, vmax) def set_data_interval(self, vmin, vmax): self.axis.set_data_interval(vmin, vmax) def set_bounds(self, vmin, vmax): self.set_view_interval(vmin, vmax) self.set_data_interval(vmin, vmax) class Formatter(TickHelper): """ Create a string based on a tick value and location. """ # some classes want to see all the locs to help format # individual ones locs = [] def __call__(self, x, pos=None): """ Return the format for tick value `x` at position pos. ``pos=None`` indicates an unspecified location. """ raise NotImplementedError('Derived must override') def format_data(self, value): """ Returns the full string representation of the value with the position unspecified. """ return self.__call__(value) def format_data_short(self, value): """ Return a short string version of the tick value. Defaults to the position-independent long value. """ return self.format_data(value) def get_offset(self): return '' def set_locs(self, locs): self.locs = locs def fix_minus(self, s): """ Some classes may want to replace a hyphen for minus with the proper unicode symbol (U+2212) for typographical correctness. The default is to not replace it. Note, if you use this method, e.g., in :meth:`format_data` or call, you probably don't want to use it for :meth:`format_data_short` since the toolbar uses this for interactive coord reporting and I doubt we can expect GUIs across platforms will handle the unicode correctly. So for now the classes that override :meth:`fix_minus` should have an explicit :meth:`format_data_short` method """ return s class IndexFormatter(Formatter): """ Format the position x to the nearest i-th label where i=int(x+0.5) """ def __init__(self, labels): self.labels = labels self.n = len(labels) def __call__(self, x, pos=None): """ Return the format for tick value `x` at position pos. The position is ignored and the value is rounded to the nearest integer, which is used to look up the label. """ i = int(x + 0.5) if i < 0 or i >= self.n: return '' else: return self.labels[i] class NullFormatter(Formatter): """ Always return the empty string. """ def __call__(self, x, pos=None): """ Returns an empty string for all inputs. """ return '' class FixedFormatter(Formatter): """ Return fixed strings for tick labels based only on position, not value. """ def __init__(self, seq): """ Set the sequence of strings that will be used for labels. """ self.seq = seq self.offset_string = '' def __call__(self, x, pos=None): """ Returns the label that matches the position regardless of the value. For positions ``pos < len(seq)``, return `seq[i]` regardless of `x`. Otherwise return empty string. `seq` is the sequence of strings that this object was initialized with. """ if pos is None or pos >= len(self.seq): return '' else: return self.seq[pos] def get_offset(self): return self.offset_string def set_offset_string(self, ofs): self.offset_string = ofs class FuncFormatter(Formatter): """ Use a user-defined function for formatting. The function should take in two inputs (a tick value ``x`` and a position ``pos``), and return a string containing the corresponding tick label. """ def __init__(self, func): self.func = func def __call__(self, x, pos=None): """ Return the value of the user defined function. `x` and `pos` are passed through as-is. """ return self.func(x, pos) class FormatStrFormatter(Formatter): """ Use an old-style ('%' operator) format string to format the tick. The format string should have a single variable format (%) in it. It will be applied to the value (not the position) of the tick. """ def __init__(self, fmt): self.fmt = fmt def __call__(self, x, pos=None): """ Return the formatted label string. Only the value `x` is formatted. The position is ignored. """ return self.fmt % x class StrMethodFormatter(Formatter): """ Use a new-style format string (as used by `str.format()`) to format the tick. The field used for the value must be labeled `x` and the field used for the position must be labeled `pos`. """ def __init__(self, fmt): self.fmt = fmt def __call__(self, x, pos=None): """ Return the formatted label string. `x` and `pos` are passed to `str.format` as keyword arguments with those exact names. """ return self.fmt.format(x=x, pos=pos) class OldScalarFormatter(Formatter): """ Tick location is a plain old number. """ def __call__(self, x, pos=None): """ Return the format for tick val `x` based on the width of the axis. The position `pos` is ignored. """ xmin, xmax = self.axis.get_view_interval() d = abs(xmax - xmin) return self.pprint_val(x, d) def pprint_val(self, x, d): """ Formats the value `x` based on the size of the axis range `d`. """ #if the number is not too big and it's an int, format it as an #int if abs(x) < 1e4 and x == int(x): return '%d' % x if d < 1e-2: fmt = '%1.3e' elif d < 1e-1: fmt = '%1.3f' elif d > 1e5: fmt = '%1.1e' elif d > 10: fmt = '%1.1f' elif d > 1: fmt = '%1.2f' else: fmt = '%1.3f' s = fmt % x tup = s.split('e') if len(tup) == 2: mantissa = tup[0].rstrip('0').rstrip('.') sign = tup[1][0].replace('+', '') exponent = tup[1][1:].lstrip('0') s = '%se%s%s' % (mantissa, sign, exponent) else: s = s.rstrip('0').rstrip('.') return s class ScalarFormatter(Formatter): """ Format tick values as a number. Tick value is interpreted as a plain old number. If ``useOffset==True`` and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for ``data < 10^-n`` or ``data >= 10^m``, where ``n`` and ``m`` are the power limits set using ``set_powerlimits((n,m))``. The defaults for these are controlled by the ``axes.formatter.limits`` rc parameter. """ def __init__(self, useOffset=None, useMathText=None, useLocale=None): # useOffset allows plotting small data ranges with large offsets: for # example: [1+1e-9,1+2e-9,1+3e-9] useMathText will render the offset # and scientific notation in mathtext if useOffset is None: useOffset = rcParams['axes.formatter.useoffset'] self._offset_threshold = rcParams['axes.formatter.offset_threshold'] self.set_useOffset(useOffset) self._usetex = rcParams['text.usetex'] if useMathText is None: useMathText = rcParams['axes.formatter.use_mathtext'] self.set_useMathText(useMathText) self.orderOfMagnitude = 0 self.format = '' self._scientific = True self._powerlimits = rcParams['axes.formatter.limits'] if useLocale is None: useLocale = rcParams['axes.formatter.use_locale'] self._useLocale = useLocale def get_useOffset(self): return self._useOffset def set_useOffset(self, val): if val in [True, False]: self.offset = 0 self._useOffset = val else: self._useOffset = False self.offset = val useOffset = property(fget=get_useOffset, fset=set_useOffset) def get_useLocale(self): return self._useLocale def set_useLocale(self, val): if val is None: self._useLocale = rcParams['axes.formatter.use_locale'] else: self._useLocale = val useLocale = property(fget=get_useLocale, fset=set_useLocale) def get_useMathText(self): return self._useMathText def set_useMathText(self, val): if val is None: self._useMathText = rcParams['axes.formatter.use_mathtext'] else: self._useMathText = val useMathText = property(fget=get_useMathText, fset=set_useMathText) def fix_minus(self, s): """ Replace hyphens with a unicode minus. """ if rcParams['text.usetex'] or not rcParams['axes.unicode_minus']: return s else: return s.replace('-', '\N{MINUS SIGN}') def __call__(self, x, pos=None): """ Return the format for tick value `x` at position `pos`. """ if len(self.locs) == 0: return '' else: s = self.pprint_val(x) return self.fix_minus(s) def set_scientific(self, b): """ Turn scientific notation on or off. .. seealso:: Method :meth:`set_powerlimits` """ self._scientific = bool(b) def set_powerlimits(self, lims): """ Sets size thresholds for scientific notation. ``lims`` is a two-element sequence containing the powers of 10 that determine the switchover threshold. Numbers below ``10**lims[0]`` and above ``10**lims[1]`` will be displayed in scientific notation. For example, ``formatter.set_powerlimits((-3, 4))`` sets the pre-2007 default in which scientific notation is used for numbers less than 1e-3 or greater than 1e4. .. seealso:: Method :meth:`set_scientific` """ if len(lims) != 2: raise ValueError("'lims' must be a sequence of length 2") self._powerlimits = lims def format_data_short(self, value): """ Return a short formatted string representation of a number. """ if self._useLocale: return locale.format_string('%-12g', (value,)) else: return '%-12g' % value def format_data(self, value): """ Return a formatted string representation of a number. """ if self._useLocale: s = locale.format_string('%1.10e', (value,)) else: s = '%1.10e' % value s = self._formatSciNotation(s) return self.fix_minus(s) def get_offset(self): """ Return scientific notation, plus offset. """ if len(self.locs) == 0: return '' s = '' if self.orderOfMagnitude or self.offset: offsetStr = '' sciNotStr = '' if self.offset: offsetStr = self.format_data(self.offset) if self.offset > 0: offsetStr = '+' + offsetStr if self.orderOfMagnitude: if self._usetex or self._useMathText: sciNotStr = self.format_data(10 ** self.orderOfMagnitude) else: sciNotStr = '1e%d' % self.orderOfMagnitude if self._useMathText: if sciNotStr != '': sciNotStr = r'\times%s' % _mathdefault(sciNotStr) s = ''.join(('$', sciNotStr, _mathdefault(offsetStr), '$')) elif self._usetex: if sciNotStr != '': sciNotStr = r'\times%s' % sciNotStr s = ''.join(('$', sciNotStr, offsetStr, '$')) else: s = ''.join((sciNotStr, offsetStr)) return self.fix_minus(s) def set_locs(self, locs): """ Set the locations of the ticks. """ self.locs = locs if len(self.locs) > 0: vmin, vmax = self.axis.get_view_interval() d = abs(vmax - vmin) if self._useOffset: self._compute_offset() self._set_orderOfMagnitude(d) self._set_format(vmin, vmax) def _compute_offset(self): locs = self.locs if locs is None or not len(locs): self.offset = 0 return # Restrict to visible ticks. vmin, vmax = sorted(self.axis.get_view_interval()) locs = np.asarray(locs) locs = locs[(vmin <= locs) & (locs <= vmax)] if not len(locs): self.offset = 0 return lmin, lmax = locs.min(), locs.max() # Only use offset if there are at least two ticks and every tick has # the same sign. if lmin == lmax or lmin <= 0 <= lmax: self.offset = 0 return # min, max comparing absolute values (we want division to round towards # zero so we work on absolute values). abs_min, abs_max = sorted([abs(float(lmin)), abs(float(lmax))]) sign = math.copysign(1, lmin) # What is the smallest power of ten such that abs_min and abs_max are # equal up to that precision? # Note: Internally using oom instead of 10 ** oom avoids some numerical # accuracy issues. oom_max = np.ceil(math.log10(abs_max)) oom = 1 + next(oom for oom in itertools.count(oom_max, -1) if abs_min // 10 ** oom != abs_max // 10 ** oom) if (abs_max - abs_min) / 10 ** oom <= 1e-2: # Handle the case of straddling a multiple of a large power of ten # (relative to the span). # What is the smallest power of ten such that abs_min and abs_max # are no more than 1 apart at that precision? oom = 1 + next(oom for oom in itertools.count(oom_max, -1) if abs_max // 10 ** oom - abs_min // 10 ** oom > 1) # Only use offset if it saves at least _offset_threshold digits. n = self._offset_threshold - 1 self.offset = (sign * (abs_max // 10 ** oom) * 10 ** oom if abs_max // 10 ** oom >= 10**n else 0) def _set_orderOfMagnitude(self, range): # if scientific notation is to be used, find the appropriate exponent # if using an numerical offset, find the exponent after applying the # offset if not self._scientific: self.orderOfMagnitude = 0 return locs = np.abs(self.locs) if self.offset: oom = math.floor(math.log10(range)) else: if locs[0] > locs[-1]: val = locs[0] else: val = locs[-1] if val == 0: oom = 0 else: oom = math.floor(math.log10(val)) if oom <= self._powerlimits[0]: self.orderOfMagnitude = oom elif oom >= self._powerlimits[1]: self.orderOfMagnitude = oom else: self.orderOfMagnitude = 0 def _set_format(self, vmin, vmax): # set the format string to format all the ticklabels if len(self.locs) < 2: # Temporarily augment the locations with the axis end points. _locs = list(self.locs) + [vmin, vmax] else: _locs = self.locs locs = (np.asarray(_locs) - self.offset) / 10. ** self.orderOfMagnitude loc_range = np.ptp(locs) # Curvilinear coordinates can yield two identical points. if loc_range == 0: loc_range = np.max(np.abs(locs)) # Both points might be zero. if loc_range == 0: loc_range = 1 if len(self.locs) < 2: # We needed the end points only for the loc_range calculation. locs = locs[:-2] loc_range_oom = int(math.floor(math.log10(loc_range))) # first estimate: sigfigs = max(0, 3 - loc_range_oom) # refined estimate: thresh = 1e-3 * 10 ** loc_range_oom while sigfigs >= 0: if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh: sigfigs -= 1 else: break sigfigs += 1 self.format = '%1.' + str(sigfigs) + 'f' if self._usetex: self.format = '$%s$' % self.format elif self._useMathText: self.format = '$%s$' % _mathdefault(self.format) def pprint_val(self, x): xp = (x - self.offset) / (10. ** self.orderOfMagnitude) if np.abs(xp) < 1e-8: xp = 0 if self._useLocale: return locale.format_string(self.format, (xp,)) else: return self.format % xp def _formatSciNotation(self, s): # transform 1e+004 into 1e4, for example if self._useLocale: decimal_point = locale.localeconv()['decimal_point'] positive_sign = locale.localeconv()['positive_sign'] else: decimal_point = '.' positive_sign = '+' tup = s.split('e') try: significand = tup[0].rstrip('0').rstrip(decimal_point) sign = tup[1][0].replace(positive_sign, '') exponent = tup[1][1:].lstrip('0') if self._useMathText or self._usetex: if significand == '1' and exponent != '': # reformat 1x10^y as 10^y significand = '' if exponent: exponent = '10^{%s%s}' % (sign, exponent) if significand and exponent: return r'%s{\times}%s' % (significand, exponent) else: return r'%s%s' % (significand, exponent) else: s = ('%se%s%s' % (significand, sign, exponent)).rstrip('e') return s except IndexError: return s class LogFormatter(Formatter): """ Base class for formatting ticks on a log or symlog scale. It may be instantiated directly, or subclassed. Parameters ---------- base : float, optional, default: 10. Base of the logarithm used in all calculations. labelOnlyBase : bool, optional, default: False If True, label ticks only at integer powers of base. This is normally True for major ticks and False for minor ticks. minor_thresholds : (subset, all), optional, default: (1, 0.4) If labelOnlyBase is False, these two numbers control the labeling of ticks that are not at integer powers of base; normally these are the minor ticks. The controlling parameter is the log of the axis data range. In the typical case where base is 10 it is the number of decades spanned by the axis, so we can call it 'numdec'. If ``numdec <= all``, all minor ticks will be labeled. If ``all < numdec <= subset``, then only a subset of minor ticks will be labeled, so as to avoid crowding. If ``numdec > subset`` then no minor ticks will be labeled. linthresh : None or float, optional, default: None If a symmetric log scale is in use, its ``linthresh`` parameter must be supplied here. Notes ----- The `set_locs` method must be called to enable the subsetting logic controlled by the ``minor_thresholds`` parameter. In some cases such as the colorbar, there is no distinction between major and minor ticks; the tick locations might be set manually, or by a locator that puts ticks at integer powers of base and at intermediate locations. For this situation, disable the minor_thresholds logic by using ``minor_thresholds=(np.inf, np.inf)``, so that all ticks will be labeled. To disable labeling of minor ticks when 'labelOnlyBase' is False, use ``minor_thresholds=(0, 0)``. This is the default for the "classic" style. Examples -------- To label a subset of minor ticks when the view limits span up to 2 decades, and all of the ticks when zoomed in to 0.5 decades or less, use ``minor_thresholds=(2, 0.5)``. To label all minor ticks when the view limits span up to 1.5 decades, use ``minor_thresholds=(1.5, 1.5)``. """ def __init__(self, base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None): self._base = float(base) self.labelOnlyBase = labelOnlyBase if minor_thresholds is None: if rcParams['_internal.classic_mode']: minor_thresholds = (0, 0) else: minor_thresholds = (1, 0.4) self.minor_thresholds = minor_thresholds self._sublabels = None self._linthresh = linthresh def base(self, base): """ change the `base` for labeling. .. warning:: Should always match the base used for :class:`LogLocator` """ self._base = base def label_minor(self, labelOnlyBase): """ Switch minor tick labeling on or off. Parameters ---------- labelOnlyBase : bool If True, label ticks only at integer powers of base. """ self.labelOnlyBase = labelOnlyBase def set_locs(self, locs=None): """ Use axis view limits to control which ticks are labeled. The ``locs`` parameter is ignored in the present algorithm. """ if np.isinf(self.minor_thresholds[0]): self._sublabels = None return # Handle symlog case: linthresh = self._linthresh if linthresh is None: try: linthresh = self.axis.get_transform().linthresh except AttributeError: pass vmin, vmax = self.axis.get_view_interval() if vmin > vmax: vmin, vmax = vmax, vmin if linthresh is None and vmin <= 0: # It's probably a colorbar with # a format kwarg setting a LogFormatter in the manner # that worked with 1.5.x, but that doesn't work now. self._sublabels = set((1,)) # label powers of base return b = self._base if linthresh is not None: # symlog # Only compute the number of decades in the logarithmic part of the # axis numdec = 0 if vmin < -linthresh: rhs = min(vmax, -linthresh) numdec += math.log(vmin / rhs) / math.log(b) if vmax > linthresh: lhs = max(vmin, linthresh) numdec += math.log(vmax / lhs) / math.log(b) else: vmin = math.log(vmin) / math.log(b) vmax = math.log(vmax) / math.log(b) numdec = abs(vmax - vmin) if numdec > self.minor_thresholds[0]: # Label only bases self._sublabels = {1} elif numdec > self.minor_thresholds[1]: # Add labels between bases at log-spaced coefficients; # include base powers in case the locations include # "major" and "minor" points, as in colorbar. c = np.logspace(0, 1, int(b)//2 + 1, base=b) self._sublabels = set(np.round(c)) # For base 10, this yields (1, 2, 3, 4, 6, 10). else: # Label all integer multiples of base**n. self._sublabels = set(np.arange(1, b + 1)) def _num_to_string(self, x, vmin, vmax): if x > 10000: s = '%1.0e' % x elif x < 1: s = '%1.0e' % x else: s = self.pprint_val(x, vmax - vmin) return s def __call__(self, x, pos=None): """ Return the format for tick val `x`. """ if x == 0.0: # Symlog return '0' x = abs(x) b = self._base # only label the decades fx = math.log(x) / math.log(b) is_x_decade = is_close_to_int(fx) exponent = np.round(fx) if is_x_decade else np.floor(fx) coeff = np.round(x / b ** exponent) if self.labelOnlyBase and not is_x_decade: return '' if self._sublabels is not None and coeff not in self._sublabels: return '' vmin, vmax = self.axis.get_view_interval() vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05) s = self._num_to_string(x, vmin, vmax) return self.fix_minus(s) def format_data(self, value): b = self.labelOnlyBase self.labelOnlyBase = False value = cbook.strip_math(self.__call__(value)) self.labelOnlyBase = b return value def format_data_short(self, value): """ Return a short formatted string representation of a number. """ return '%-12g' % value def pprint_val(self, x, d): #if the number is not too big and it's an int, format it as an #int if abs(x) < 1e4 and x == int(x): return '%d' % x if d < 1e-2: fmt = '%1.3e' elif d < 1e-1: fmt = '%1.3f' elif d > 1e5: fmt = '%1.1e' elif d > 10: fmt = '%1.1f' elif d > 1: fmt = '%1.2f' else: fmt = '%1.3f' s = fmt % x tup = s.split('e') if len(tup) == 2: mantissa = tup[0].rstrip('0').rstrip('.') exponent = int(tup[1]) if exponent: s = '%se%d' % (mantissa, exponent) else: s = mantissa else: s = s.rstrip('0').rstrip('.') return s class LogFormatterExponent(LogFormatter): """ Format values for log axis using ``exponent = log_base(value)``. """ def _num_to_string(self, x, vmin, vmax): fx = math.log(x) / math.log(self._base) if abs(fx) > 10000: s = '%1.0g' % fx elif abs(fx) < 1: s = '%1.0g' % fx else: fd = math.log(vmax - vmin) / math.log(self._base) s = self.pprint_val(fx, fd) return s class LogFormatterMathtext(LogFormatter): """ Format values for log axis using ``exponent = log_base(value)``. """ def _non_decade_format(self, sign_string, base, fx, usetex): 'Return string for non-decade locations' if usetex: return (r'$%s%s^{%.2f}$') % (sign_string, base, fx) else: return ('$%s$' % _mathdefault('%s%s^{%.2f}' % (sign_string, base, fx))) def __call__(self, x, pos=None): """ Return the format for tick value `x`. The position `pos` is ignored. """ usetex = rcParams['text.usetex'] min_exp = rcParams['axes.formatter.min_exponent'] if x == 0: # Symlog if usetex: return '$0$' else: return '$%s$' % _mathdefault('0') sign_string = '-' if x < 0 else '' x = abs(x) b = self._base # only label the decades fx = math.log(x) / math.log(b) is_x_decade = is_close_to_int(fx) exponent = np.round(fx) if is_x_decade else np.floor(fx) coeff = np.round(x / b ** exponent) if is_x_decade: fx = nearest_long(fx) if self.labelOnlyBase and not is_x_decade: return '' if self._sublabels is not None and coeff not in self._sublabels: return '' # use string formatting of the base if it is not an integer if b % 1 == 0.0: base = '%d' % b else: base = '%s' % b if np.abs(fx) < min_exp: if usetex: return r'${0}{1:g}$'.format(sign_string, x) else: return '${0}$'.format(_mathdefault( '{0}{1:g}'.format(sign_string, x))) elif not is_x_decade: return self._non_decade_format(sign_string, base, fx, usetex) else: if usetex: return (r'$%s%s^{%d}$') % (sign_string, base, nearest_long(fx)) else: return ('$%s$' % _mathdefault( '%s%s^{%d}' % (sign_string, base, nearest_long(fx)))) class LogFormatterSciNotation(LogFormatterMathtext): """ Format values following scientific notation in a logarithmic axis """ def _non_decade_format(self, sign_string, base, fx, usetex): 'Return string for non-decade locations' b = float(base) exponent = math.floor(fx) coeff = b ** fx / b ** exponent if is_close_to_int(coeff): coeff = nearest_long(coeff) if usetex: return (r'$%s%g\times%s^{%d}$') % \ (sign_string, coeff, base, exponent) else: return ('$%s$' % _mathdefault(r'%s%g\times%s^{%d}' % (sign_string, coeff, base, exponent))) class LogitFormatter(Formatter): """ Probability formatter (using Math text). """ def __call__(self, x, pos=None): s = '' if 0.01 <= x <= 0.99: s = '{:.2f}'.format(x) elif x < 0.01: if is_decade(x): s = '$10^{{{:.0f}}}$'.format(np.log10(x)) else: s = '${:.5f}$'.format(x) else: # x > 0.99 if is_decade(1-x): s = '$1-10^{{{:.0f}}}$'.format(np.log10(1-x)) else: s = '$1-{:.5f}$'.format(1-x) return s def format_data_short(self, value): 'return a short formatted string representation of a number' return '%-12g' % value class EngFormatter(Formatter): """ Formats axis values using engineering prefixes to represent powers of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7. """ # The SI engineering prefixes ENG_PREFIXES = { -24: "y", -21: "z", -18: "a", -15: "f", -12: "p", -9: "n", -6: "\N{GREEK SMALL LETTER MU}", -3: "m", 0: "", 3: "k", 6: "M", 9: "G", 12: "T", 15: "P", 18: "E", 21: "Z", 24: "Y" } def __init__(self, unit="", places=None, sep=" "): """ Parameters ---------- unit : str (default: "") Unit symbol to use, suitable for use with single-letter representations of powers of 1000. For example, 'Hz' or 'm'. places : int (default: None) Precision with which to display the number, specified in digits after the decimal point (there will be between one and three digits before the decimal point). If it is None, the formatting falls back to the floating point format '%g', which displays up to 6 *significant* digits, i.e. the equivalent value for *places* varies between 0 and 5 (inclusive). sep : str (default: " ") Separator used between the value and the prefix/unit. For example, one get '3.14 mV' if ``sep`` is " " (default) and '3.14mV' if ``sep`` is "". Besides the default behavior, some other useful options may be: * ``sep=""`` to append directly the prefix/unit to the value; * ``sep="\\N{THIN SPACE}"`` (``U+2009``); * ``sep="\\N{NARROW NO-BREAK SPACE}"`` (``U+202F``); * ``sep="\\N{NO-BREAK SPACE}"`` (``U+00A0``). """ self.unit = unit self.places = places self.sep = sep def __call__(self, x, pos=None): s = "%s%s" % (self.format_eng(x), self.unit) # Remove the trailing separator when there is neither prefix nor unit if len(self.sep) > 0 and s.endswith(self.sep): s = s[:-len(self.sep)] return self.fix_minus(s) def format_eng(self, num): """ Formats a number in engineering notation, appending a letter representing the power of 1000 of the original number. Some examples: >>> format_eng(0) # for self.places = 0 '0' >>> format_eng(1000000) # for self.places = 1 '1.0 M' >>> format_eng("-1e-6") # for self.places = 2 u'-1.00 \N{GREEK SMALL LETTER MU}' `num` may be a numeric value or a string that can be converted to a numeric value with ``float(num)``. """ if isinstance(num, six.string_types): warnings.warn( "Passing a string as *num* argument is deprecated since" "Matplotlib 2.1, and is expected to be removed in 2.3.", mplDeprecation) dnum = float(num) sign = 1 fmt = "g" if self.places is None else ".{:d}f".format(self.places) if dnum < 0: sign = -1 dnum = -dnum if dnum != 0: pow10 = int(math.floor(math.log10(dnum) / 3) * 3) else: pow10 = 0 # Force dnum to zero, to avoid inconsistencies like # format_eng(-0) = "0" and format_eng(0.0) = "0" # but format_eng(-0.0) = "-0.0" dnum = 0.0 pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES)) mant = sign * dnum / (10.0 ** pow10) # Taking care of the cases like 999.9..., which # may be rounded to 1000 instead of 1 k. Beware # of the corner case of values that are beyond # the range of SI prefixes (i.e. > 'Y'). _fmant = float("{mant:{fmt}}".format(mant=mant, fmt=fmt)) if _fmant >= 1000 and pow10 != max(self.ENG_PREFIXES): mant /= 1000 pow10 += 3 prefix = self.ENG_PREFIXES[int(pow10)] formatted = "{mant:{fmt}}{sep}{prefix}".format( mant=mant, sep=self.sep, prefix=prefix, fmt=fmt) return formatted class PercentFormatter(Formatter): """ Format numbers as a percentage. How the number is converted into a percentage is determined by the `xmax` parameter. `xmax` is the data value that corresponds to 100%. Percentages are computed as ``x / xmax * 100``. So if the data is already scaled to be percentages, `xmax` will be 100. Another common situation is where `xmax` is 1.0. `symbol` is a string which will be appended to the label. It may be `None` or empty to indicate that no symbol should be used. LaTeX special characters are escaped in `symbol` whenever latex mode is enabled, unless `is_latex` is `True`. `decimals` is the number of decimal places to place after the point. If it is set to `None` (the default), the number will be computed automatically. """ def __init__(self, xmax=100, decimals=None, symbol='%', is_latex=False): self.xmax = xmax + 0.0 self.decimals = decimals self._symbol = symbol self._is_latex = is_latex def __call__(self, x, pos=None): """ Formats the tick as a percentage with the appropriate scaling. """ ax_min, ax_max = self.axis.get_view_interval() display_range = abs(ax_max - ax_min) return self.fix_minus(self.format_pct(x, display_range)) def format_pct(self, x, display_range): """ Formats the number as a percentage number with the correct number of decimals and adds the percent symbol, if any. If `self.decimals` is `None`, the number of digits after the decimal point is set based on the `display_range` of the axis as follows: +---------------+----------+------------------------+ | display_range | decimals | sample | +---------------+----------+------------------------+ | >50 | 0 | ``x = 34.5`` => 35% | +---------------+----------+------------------------+ | >5 | 1 | ``x = 34.5`` => 34.5% | +---------------+----------+------------------------+ | >0.5 | 2 | ``x = 34.5`` => 34.50% | +---------------+----------+------------------------+ | ... | ... | ... | +---------------+----------+------------------------+ This method will not be very good for tiny axis ranges or extremely large ones. It assumes that the values on the chart are percentages displayed on a reasonable scale. """ x = self.convert_to_pct(x) if self.decimals is None: # conversion works because display_range is a difference scaled_range = self.convert_to_pct(display_range) if scaled_range <= 0: decimals = 0 else: # Luckily Python's built-in ceil rounds to +inf, not away from # zero. This is very important since the equation for decimals # starts out as `scaled_range > 0.5 * 10**(2 - decimals)` # and ends up with `decimals > 2 - log10(2 * scaled_range)`. decimals = math.ceil(2.0 - math.log10(2.0 * scaled_range)) if decimals > 5: decimals = 5 elif decimals < 0: decimals = 0 else: decimals = self.decimals s = '{x:0.{decimals}f}'.format(x=x, decimals=int(decimals)) return s + self.symbol def convert_to_pct(self, x): return 100.0 * (x / self.xmax) @property def symbol(self): """ The configured percent symbol as a string. If LaTeX is enabled via :rc:`text.usetex`, the special characters ``{'#', '$', '%', '&', '~', '_', '^', '\\', '{', '}'}`` are automatically escaped in the string. """ symbol = self._symbol if not symbol: symbol = '' elif rcParams['text.usetex'] and not self._is_latex: # Source: http://www.personal.ceu.hu/tex/specchar.htm # Backslash must be first for this to work correctly since # it keeps getting added in for spec in r'\#$%&~_^{}': symbol = symbol.replace(spec, '\\' + spec) return symbol @symbol.setter def symbol(self, symbol): self._symbol = symbol class Locator(TickHelper): """ Determine the tick locations; Note, you should not use the same locator between different :class:`~matplotlib.axis.Axis` because the locator stores references to the Axis data and view limits """ # Some automatic tick locators can generate so many ticks they # kill the machine when you try and render them. # This parameter is set to cause locators to raise an error if too # many ticks are generated. MAXTICKS = 1000 def tick_values(self, vmin, vmax): """ Return the values of the located ticks given **vmin** and **vmax**. .. note:: To get tick locations with the vmin and vmax values defined automatically for the associated :attr:`axis` simply call the Locator instance:: >>> print((type(loc))) <type 'Locator'> >>> print((loc())) [1, 2, 3, 4] """ raise NotImplementedError('Derived must override') def set_params(self, **kwargs): """ Do nothing, and rase a warning. Any locator class not supporting the set_params() function will call this. """ warnings.warn("'set_params()' not defined for locator of type " + str(type(self))) def __call__(self): """Return the locations of the ticks""" # note: some locators return data limits, other return view limits, # hence there is no *one* interface to call self.tick_values. raise NotImplementedError('Derived must override') def raise_if_exceeds(self, locs): """raise a RuntimeError if Locator attempts to create more than MAXTICKS locs""" if len(locs) >= self.MAXTICKS: raise RuntimeError("Locator attempting to generate {} ticks from " "{} to {}: exceeds Locator.MAXTICKS".format( len(locs), locs[0], locs[-1])) return locs def view_limits(self, vmin, vmax): """ select a scale for the range from vmin to vmax Normally this method is overridden by subclasses to change locator behaviour. """ return mtransforms.nonsingular(vmin, vmax) def autoscale(self): """autoscale the view limits""" return self.view_limits(*self.axis.get_view_interval()) def pan(self, numsteps): """Pan numticks (can be positive or negative)""" ticks = self() numticks = len(ticks) vmin, vmax = self.axis.get_view_interval() vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05) if numticks > 2: step = numsteps * abs(ticks[0] - ticks[1]) else: d = abs(vmax - vmin) step = numsteps * d / 6. vmin += step vmax += step self.axis.set_view_interval(vmin, vmax, ignore=True) def zoom(self, direction): "Zoom in/out on axis; if direction is >0 zoom in, else zoom out" vmin, vmax = self.axis.get_view_interval() vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05) interval = abs(vmax - vmin) step = 0.1 * interval * direction self.axis.set_view_interval(vmin + step, vmax - step, ignore=True) def refresh(self): """refresh internal information based on current lim""" pass class IndexLocator(Locator): """ Place a tick on every multiple of some base number of points plotted, e.g., on every 5th point. It is assumed that you are doing index plotting; i.e., the axis is 0, len(data). This is mainly useful for x ticks. """ def __init__(self, base, offset): 'place ticks on the i-th data points where (i-offset)%base==0' self._base = base self.offset = offset def set_params(self, base=None, offset=None): """Set parameters within this locator""" if base is not None: self._base = base if offset is not None: self.offset = offset def __call__(self): """Return the locations of the ticks""" dmin, dmax = self.axis.get_data_interval() return self.tick_values(dmin, dmax) def tick_values(self, vmin, vmax): return self.raise_if_exceeds( np.arange(vmin + self.offset, vmax + 1, self._base)) class FixedLocator(Locator): """ Tick locations are fixed. If nbins is not None, the array of possible positions will be subsampled to keep the number of ticks <= nbins +1. The subsampling will be done so as to include the smallest absolute value; for example, if zero is included in the array of possibilities, then it is guaranteed to be one of the chosen ticks. """ def __init__(self, locs, nbins=None): self.locs = np.asarray(locs) self.nbins = nbins if self.nbins is not None: self.nbins = max(self.nbins, 2) def set_params(self, nbins=None): """Set parameters within this locator.""" if nbins is not None: self.nbins = nbins def __call__(self): return self.tick_values(None, None) def tick_values(self, vmin, vmax): """" Return the locations of the ticks. .. note:: Because the values are fixed, vmin and vmax are not used in this method. """ if self.nbins is None: return self.locs step = max(int(np.ceil(len(self.locs) / self.nbins)), 1) ticks = self.locs[::step] for i in range(1, step): ticks1 = self.locs[i::step] if np.abs(ticks1).min() < np.abs(ticks).min(): ticks = ticks1 return self.raise_if_exceeds(ticks) class NullLocator(Locator): """ No ticks """ def __call__(self): return self.tick_values(None, None) def tick_values(self, vmin, vmax): """" Return the locations of the ticks. .. note:: Because the values are Null, vmin and vmax are not used in this method. """ return [] class LinearLocator(Locator): """ Determine the tick locations The first time this function is called it will try to set the number of ticks to make a nice tick partitioning. Thereafter the number of ticks will be fixed so that interactive navigation will be nice """ def __init__(self, numticks=None, presets=None): """ Use presets to set locs based on lom. A dict mapping vmin, vmax->locs """ self.numticks = numticks if presets is None: self.presets = {} else: self.presets = presets def set_params(self, numticks=None, presets=None): """Set parameters within this locator.""" if presets is not None: self.presets = presets if numticks is not None: self.numticks = numticks def __call__(self): 'Return the locations of the ticks' vmin, vmax = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05) if vmax < vmin: vmin, vmax = vmax, vmin if (vmin, vmax) in self.presets: return self.presets[(vmin, vmax)] if self.numticks is None: self._set_numticks() if self.numticks == 0: return [] ticklocs = np.linspace(vmin, vmax, self.numticks) return self.raise_if_exceeds(ticklocs) def _set_numticks(self): self.numticks = 11 # todo; be smart here; this is just for dev def view_limits(self, vmin, vmax): 'Try to choose the view limits intelligently' if vmax < vmin: vmin, vmax = vmax, vmin if vmin == vmax: vmin -= 1 vmax += 1 if rcParams['axes.autolimit_mode'] == 'round_numbers': exponent, remainder = _divmod( math.log10(vmax - vmin), math.log10(max(self.numticks - 1, 1))) exponent -= (remainder < .5) scale = max(self.numticks - 1, 1) ** (-exponent) vmin = math.floor(scale * vmin) / scale vmax = math.ceil(scale * vmax) / scale return mtransforms.nonsingular(vmin, vmax) def closeto(x, y): if abs(x - y) < 1e-10: return True else: return False class Base(object): 'this solution has some hacks to deal with floating point inaccuracies' def __init__(self, base): if base <= 0: raise ValueError("'base' must be positive") self._base = base def lt(self, x): 'return the largest multiple of base < x' d, m = _divmod(x, self._base) if closeto(m, 0) and not closeto(m / self._base, 1): return (d - 1) * self._base return d * self._base def le(self, x): 'return the largest multiple of base <= x' d, m = _divmod(x, self._base) if closeto(m / self._base, 1): # was closeto(m, self._base) #looks like floating point error return (d + 1) * self._base return d * self._base def gt(self, x): 'return the smallest multiple of base > x' d, m = _divmod(x, self._base) if closeto(m / self._base, 1): #looks like floating point error return (d + 2) * self._base return (d + 1) * self._base def ge(self, x): 'return the smallest multiple of base >= x' d, m = _divmod(x, self._base) if closeto(m, 0) and not closeto(m / self._base, 1): return d * self._base return (d + 1) * self._base def get_base(self): return self._base class MultipleLocator(Locator): """ Set a tick on every integer that is multiple of base in the view interval """ def __init__(self, base=1.0): self._base = Base(base) def set_params(self, base): """Set parameters within this locator.""" if base is not None: self._base = base def __call__(self): 'Return the locations of the ticks' vmin, vmax = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): if vmax < vmin: vmin, vmax = vmax, vmin vmin = self._base.ge(vmin) base = self._base.get_base() n = (vmax - vmin + 0.001 * base) // base locs = vmin - base + np.arange(n + 3) * base return self.raise_if_exceeds(locs) def view_limits(self, dmin, dmax): """ Set the view limits to the nearest multiples of base that contain the data """ if rcParams['axes.autolimit_mode'] == 'round_numbers': vmin = self._base.le(dmin) vmax = self._base.ge(dmax) if vmin == vmax: vmin -= 1 vmax += 1 else: vmin = dmin vmax = dmax return mtransforms.nonsingular(vmin, vmax) def scale_range(vmin, vmax, n=1, threshold=100): dv = abs(vmax - vmin) # > 0 as nonsingular is called before. meanv = (vmax + vmin) / 2 if abs(meanv) / dv < threshold: offset = 0 else: offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv) scale = 10 ** (math.log10(dv / n) // 1) return scale, offset class MaxNLocator(Locator): """ Select no more than N intervals at nice locations. """ default_params = dict(nbins=10, steps=None, integer=False, symmetric=False, prune=None, min_n_ticks=2) def __init__(self, *args, **kwargs): """ Keyword args: *nbins* Maximum number of intervals; one less than max number of ticks. If the string `'auto'`, the number of bins will be automatically determined based on the length of the axis. *steps* Sequence of nice numbers starting with 1 and ending with 10; e.g., [1, 2, 4, 5, 10], where the values are acceptable tick multiples. i.e. for the example, 20, 40, 60 would be an acceptable set of ticks, as would 0.4, 0.6, 0.8, because they are multiples of 2. However, 30, 60, 90 would not be allowed because 3 does not appear in the list of steps. *integer* If True, ticks will take only integer values, provided at least `min_n_ticks` integers are found within the view limits. *symmetric* If True, autoscaling will result in a range symmetric about zero. *prune* ['lower' | 'upper' | 'both' | None] Remove edge ticks -- useful for stacked or ganged plots where the upper tick of one axes overlaps with the lower tick of the axes above it, primarily when :rc:`axes.autolimit_mode` is ``'round_numbers'``. If ``prune=='lower'``, the smallest tick will be removed. If ``prune == 'upper'``, the largest tick will be removed. If ``prune == 'both'``, the largest and smallest ticks will be removed. If ``prune == None``, no ticks will be removed. *min_n_ticks* Relax `nbins` and `integer` constraints if necessary to obtain this minimum number of ticks. """ if args: kwargs['nbins'] = args[0] if len(args) > 1: raise ValueError( "Keywords are required for all arguments except 'nbins'") self.set_params(**self.default_params) self.set_params(**kwargs) @staticmethod def _validate_steps(steps): if not np.iterable(steps): raise ValueError('steps argument must be a sequence of numbers ' 'from 1 to 10') steps = np.asarray(steps) if np.any(np.diff(steps) <= 0): raise ValueError('steps argument must be uniformly increasing') if steps[-1] > 10 or steps[0] < 1: warnings.warn('Steps argument should be a sequence of numbers\n' 'increasing from 1 to 10, inclusive. Behavior with\n' 'values outside this range is undefined, and will\n' 'raise a ValueError in future versions of mpl.') if steps[0] != 1: steps = np.hstack((1, steps)) if steps[-1] != 10: steps = np.hstack((steps, 10)) return steps @staticmethod def _staircase(steps): # Make an extended staircase within which the needed # step will be found. This is probably much larger # than necessary. flights = (0.1 * steps[:-1], steps, 10 * steps[1]) return np.hstack(flights) def set_params(self, **kwargs): """Set parameters within this locator.""" if 'nbins' in kwargs: self._nbins = kwargs['nbins'] if self._nbins != 'auto': self._nbins = int(self._nbins) if 'symmetric' in kwargs: self._symmetric = kwargs['symmetric'] if 'prune' in kwargs: prune = kwargs['prune'] if prune is not None and prune not in ['upper', 'lower', 'both']: raise ValueError( "prune must be 'upper', 'lower', 'both', or None") self._prune = prune if 'min_n_ticks' in kwargs: self._min_n_ticks = max(1, kwargs['min_n_ticks']) if 'steps' in kwargs: steps = kwargs['steps'] if steps is None: self._steps = np.array([1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) else: self._steps = self._validate_steps(steps) self._extended_steps = self._staircase(self._steps) if 'integer' in kwargs: self._integer = kwargs['integer'] def _raw_ticks(self, vmin, vmax): if self._nbins == 'auto': if self.axis is not None: nbins = np.clip(self.axis.get_tick_space(), max(1, self._min_n_ticks - 1), 9) else: nbins = 9 else: nbins = self._nbins scale, offset = scale_range(vmin, vmax, nbins) _vmin = vmin - offset _vmax = vmax - offset raw_step = (vmax - vmin) / nbins steps = self._extended_steps * scale if self._integer: # For steps > 1, keep only integer values. igood = (steps < 1) | (np.abs(steps - np.round(steps)) < 0.001) steps = steps[igood] istep = np.nonzero(steps >= raw_step)[0][0] # Classic round_numbers mode may require a larger step. if rcParams['axes.autolimit_mode'] == 'round_numbers': for istep in range(istep, len(steps)): step = steps[istep] best_vmin = (_vmin // step) * step best_vmax = best_vmin + step * nbins if (best_vmax >= _vmax): break # This is an upper limit; move to smaller steps if necessary. for i in range(istep): step = steps[istep - i] if (self._integer and np.floor(_vmax) - np.ceil(_vmin) >= self._min_n_ticks - 1): step = max(1, step) best_vmin = (_vmin // step) * step low = np.round(Base(step).le(_vmin - best_vmin) / step) high = np.round(Base(step).ge(_vmax - best_vmin) / step) ticks = np.arange(low, high + 1) * step + best_vmin + offset nticks = ((ticks <= vmax) & (ticks >= vmin)).sum() if nticks >= self._min_n_ticks: break return ticks def __call__(self): vmin, vmax = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): if self._symmetric: vmax = max(abs(vmin), abs(vmax)) vmin = -vmax vmin, vmax = mtransforms.nonsingular( vmin, vmax, expander=1e-13, tiny=1e-14) locs = self._raw_ticks(vmin, vmax) prune = self._prune if prune == 'lower': locs = locs[1:] elif prune == 'upper': locs = locs[:-1] elif prune == 'both': locs = locs[1:-1] return self.raise_if_exceeds(locs) def view_limits(self, dmin, dmax): if self._symmetric: dmax = max(abs(dmin), abs(dmax)) dmin = -dmax dmin, dmax = mtransforms.nonsingular( dmin, dmax, expander=1e-12, tiny=1e-13) if rcParams['axes.autolimit_mode'] == 'round_numbers': return self._raw_ticks(dmin, dmax)[[0, -1]] else: return dmin, dmax def decade_down(x, base=10): 'floor x to the nearest lower decade' if x == 0.0: return -base lx = np.floor(np.log(x) / np.log(base)) return base ** lx def decade_up(x, base=10): 'ceil x to the nearest higher decade' if x == 0.0: return base lx = np.ceil(np.log(x) / np.log(base)) return base ** lx def nearest_long(x): if x == 0: return long(0) elif x > 0: return long(x + 0.5) else: return long(x - 0.5) def is_decade(x, base=10): if not np.isfinite(x): return False if x == 0.0: return True lx = np.log(np.abs(x)) / np.log(base) return is_close_to_int(lx) def is_close_to_int(x): if not np.isfinite(x): return False return abs(x - nearest_long(x)) < 1e-10 class LogLocator(Locator): """ Determine the tick locations for log axes """ def __init__(self, base=10.0, subs=(1.0,), numdecs=4, numticks=None): """ Place ticks on the locations : subs[j] * base**i Parameters ---------- subs : None, string, or sequence of float, optional, default (1.0,) Gives the multiples of integer powers of the base at which to place ticks. The default places ticks only at integer powers of the base. The permitted string values are ``'auto'`` and ``'all'``, both of which use an algorithm based on the axis view limits to determine whether and how to put ticks between integer powers of the base. With ``'auto'``, ticks are placed only between integer powers; with ``'all'``, the integer powers are included. A value of None is equivalent to ``'auto'``. """ if numticks is None: if rcParams['_internal.classic_mode']: numticks = 15 else: numticks = 'auto' self.base(base) self.subs(subs) self.numdecs = numdecs self.numticks = numticks def set_params(self, base=None, subs=None, numdecs=None, numticks=None): """Set parameters within this locator.""" if base is not None: self.base(base) if subs is not None: self.subs(subs) if numdecs is not None: self.numdecs = numdecs if numticks is not None: self.numticks = numticks # FIXME: these base and subs functions are contrary to our # usual and desired API. def base(self, base): """ set the base of the log scaling (major tick every base**i, i integer) """ self._base = float(base) def subs(self, subs): """ set the minor ticks for the log scaling every base**i*subs[j] """ if subs is None: # consistency with previous bad API self._subs = 'auto' elif isinstance(subs, six.string_types): if subs not in ('all', 'auto'): raise ValueError("A subs string must be 'all' or 'auto'; " "found '%s'." % subs) self._subs = subs else: self._subs = np.asarray(subs, dtype=float) def __call__(self): 'Return the locations of the ticks' vmin, vmax = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): if self.numticks == 'auto': if self.axis is not None: numticks = np.clip(self.axis.get_tick_space(), 2, 9) else: numticks = 9 else: numticks = self.numticks b = self._base # dummy axis has no axes attribute if hasattr(self.axis, 'axes') and self.axis.axes.name == 'polar': vmax = math.ceil(math.log(vmax) / math.log(b)) decades = np.arange(vmax - self.numdecs, vmax) ticklocs = b ** decades return ticklocs if vmin <= 0.0: if self.axis is not None: vmin = self.axis.get_minpos() if vmin <= 0.0 or not np.isfinite(vmin): raise ValueError( "Data has no positive values, and therefore can not be " "log-scaled.") vmin = math.log(vmin) / math.log(b) vmax = math.log(vmax) / math.log(b) if vmax < vmin: vmin, vmax = vmax, vmin numdec = math.floor(vmax) - math.ceil(vmin) if isinstance(self._subs, six.string_types): _first = 2.0 if self._subs == 'auto' else 1.0 if numdec > 10 or b < 3: if self._subs == 'auto': return np.array([]) # no minor or major ticks else: subs = np.array([1.0]) # major ticks else: subs = np.arange(_first, b) else: subs = self._subs stride = 1 if rcParams['_internal.classic_mode']: # Leave the bug left over from the PY2-PY3 transition. while numdec / stride + 1 > numticks: stride += 1 else: while numdec // stride + 1 > numticks: stride += 1 # Does subs include anything other than 1? have_subs = len(subs) > 1 or (len(subs == 1) and subs[0] != 1.0) decades = np.arange(math.floor(vmin) - stride, math.ceil(vmax) + 2 * stride, stride) if hasattr(self, '_transform'): ticklocs = self._transform.inverted().transform(decades) if have_subs: if stride == 1: ticklocs = np.ravel(np.outer(subs, ticklocs)) else: ticklocs = [] else: if have_subs: ticklocs = [] if stride == 1: for decadeStart in b ** decades: ticklocs.extend(subs * decadeStart) else: ticklocs = b ** decades return self.raise_if_exceeds(np.asarray(ticklocs)) def view_limits(self, vmin, vmax): 'Try to choose the view limits intelligently' b = self._base vmin, vmax = self.nonsingular(vmin, vmax) if self.axis.axes.name == 'polar': vmax = math.ceil(math.log(vmax) / math.log(b)) vmin = b ** (vmax - self.numdecs) if rcParams['axes.autolimit_mode'] == 'round_numbers': if not is_decade(vmin, self._base): vmin = decade_down(vmin, self._base) if not is_decade(vmax, self._base): vmax = decade_up(vmax, self._base) return vmin, vmax def nonsingular(self, vmin, vmax): if not np.isfinite(vmin) or not np.isfinite(vmax): return 1, 10 # initial range, no data plotted yet if vmin > vmax: vmin, vmax = vmax, vmin if vmax <= 0: warnings.warn( "Data has no positive values, and therefore cannot be " "log-scaled.") return 1, 10 minpos = self.axis.get_minpos() if not np.isfinite(minpos): minpos = 1e-300 # This should never take effect. if vmin <= 0: vmin = minpos if vmin == vmax: vmin = decade_down(vmin, self._base) vmax = decade_up(vmax, self._base) return vmin, vmax class SymmetricalLogLocator(Locator): """ Determine the tick locations for symmetric log axes """ def __init__(self, transform=None, subs=None, linthresh=None, base=None): """ place ticks on the location= base**i*subs[j] """ if transform is not None: self._base = transform.base self._linthresh = transform.linthresh elif linthresh is not None and base is not None: self._base = base self._linthresh = linthresh else: raise ValueError("Either transform, or both linthresh " "and base, must be provided.") if subs is None: self._subs = [1.0] else: self._subs = subs self.numticks = 15 def set_params(self, subs=None, numticks=None): """Set parameters within this locator.""" if numticks is not None: self.numticks = numticks if subs is not None: self._subs = subs def __call__(self): 'Return the locations of the ticks' # Note, these are untransformed coordinates vmin, vmax = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): b = self._base t = self._linthresh if vmax < vmin: vmin, vmax = vmax, vmin # The domain is divided into three sections, only some of # which may actually be present. # # <======== -t ==0== t ========> # aaaaaaaaa bbbbb ccccccccc # # a) and c) will have ticks at integral log positions. The # number of ticks needs to be reduced if there are more # than self.numticks of them. # # b) has a tick at 0 and only 0 (we assume t is a small # number, and the linear segment is just an implementation # detail and not interesting.) # # We could also add ticks at t, but that seems to usually be # uninteresting. # # "simple" mode is when the range falls entirely within (-t, # t) -- it should just display (vmin, 0, vmax) has_a = has_b = has_c = False if vmin < -t: has_a = True if vmax > -t: has_b = True if vmax > t: has_c = True elif vmin < 0: if vmax > 0: has_b = True if vmax > t: has_c = True else: return [vmin, vmax] elif vmin < t: if vmax > t: has_b = True has_c = True else: return [vmin, vmax] else: has_c = True def get_log_range(lo, hi): lo = np.floor(np.log(lo) / np.log(b)) hi = np.ceil(np.log(hi) / np.log(b)) return lo, hi # First, calculate all the ranges, so we can determine striding if has_a: if has_b: a_range = get_log_range(t, -vmin + 1) else: a_range = get_log_range(-vmax, -vmin + 1) else: a_range = (0, 0) if has_c: if has_b: c_range = get_log_range(t, vmax + 1) else: c_range = get_log_range(vmin, vmax + 1) else: c_range = (0, 0) total_ticks = (a_range[1] - a_range[0]) + (c_range[1] - c_range[0]) if has_b: total_ticks += 1 stride = max(total_ticks // (self.numticks - 1), 1) decades = [] if has_a: decades.extend(-1 * (b ** (np.arange(a_range[0], a_range[1], stride)[::-1]))) if has_b: decades.append(0.0) if has_c: decades.extend(b ** (np.arange(c_range[0], c_range[1], stride))) # Add the subticks if requested if self._subs is None: subs = np.arange(2.0, b) else: subs = np.asarray(self._subs) if len(subs) > 1 or subs[0] != 1.0: ticklocs = [] for decade in decades: if decade == 0: ticklocs.append(decade) else: ticklocs.extend(subs * decade) else: ticklocs = decades return self.raise_if_exceeds(np.array(ticklocs)) def view_limits(self, vmin, vmax): 'Try to choose the view limits intelligently' b = self._base if vmax < vmin: vmin, vmax = vmax, vmin if rcParams['axes.autolimit_mode'] == 'round_numbers': if not is_decade(abs(vmin), b): if vmin < 0: vmin = -decade_up(-vmin, b) else: vmin = decade_down(vmin, b) if not is_decade(abs(vmax), b): if vmax < 0: vmax = -decade_down(-vmax, b) else: vmax = decade_up(vmax, b) if vmin == vmax: if vmin < 0: vmin = -decade_up(-vmin, b) vmax = -decade_down(-vmax, b) else: vmin = decade_down(vmin, b) vmax = decade_up(vmax, b) result = mtransforms.nonsingular(vmin, vmax) return result class LogitLocator(Locator): """ Determine the tick locations for logit axes """ def __init__(self, minor=False): """ place ticks on the logit locations """ self.minor = minor def set_params(self, minor=None): """Set parameters within this locator.""" if minor is not None: self.minor = minor def __call__(self): 'Return the locations of the ticks' vmin, vmax = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): # dummy axis has no axes attribute if hasattr(self.axis, 'axes') and self.axis.axes.name == 'polar': raise NotImplementedError('Polar axis cannot be logit scaled yet') vmin, vmax = self.nonsingular(vmin, vmax) vmin = np.log10(vmin / (1 - vmin)) vmax = np.log10(vmax / (1 - vmax)) decade_min = np.floor(vmin) decade_max = np.ceil(vmax) # major ticks if not self.minor: ticklocs = [] if (decade_min <= -1): expo = np.arange(decade_min, min(0, decade_max + 1)) ticklocs.extend(list(10**expo)) if (decade_min <= 0) and (decade_max >= 0): ticklocs.append(0.5) if (decade_max >= 1): expo = -np.arange(max(1, decade_min), decade_max + 1) ticklocs.extend(list(1 - 10**expo)) # minor ticks else: ticklocs = [] if (decade_min <= -2): expo = np.arange(decade_min, min(-1, decade_max)) newticks = np.outer(np.arange(2, 10), 10**expo).ravel() ticklocs.extend(list(newticks)) if (decade_min <= 0) and (decade_max >= 0): ticklocs.extend([0.2, 0.3, 0.4, 0.6, 0.7, 0.8]) if (decade_max >= 2): expo = -np.arange(max(2, decade_min), decade_max + 1) newticks = 1 - np.outer(np.arange(2, 10), 10**expo).ravel() ticklocs.extend(list(newticks)) return self.raise_if_exceeds(np.array(ticklocs)) def nonsingular(self, vmin, vmax): initial_range = (1e-7, 1 - 1e-7) if not np.isfinite(vmin) or not np.isfinite(vmax): return initial_range # no data plotted yet if vmin > vmax: vmin, vmax = vmax, vmin # what to do if a window beyond ]0, 1[ is chosen if self.axis is not None: minpos = self.axis.get_minpos() if not np.isfinite(minpos): return initial_range # again, no data plotted else: minpos = 1e-7 # should not occur in normal use # NOTE: for vmax, we should query a property similar to get_minpos, but # related to the maximal, less-than-one data point. Unfortunately, # Bbox._minpos is defined very deep in the BBox and updated with data, # so for now we use 1 - minpos as a substitute. if vmin <= 0: vmin = minpos if vmax >= 1: vmax = 1 - minpos if vmin == vmax: return 0.1 * vmin, 1 - 0.1 * vmin return vmin, vmax class AutoLocator(MaxNLocator): """ Dynamically find major tick positions. This is actually a subclass of `~matplotlib.ticker.MaxNLocator`, with parameters *nbins = 'auto'* and *steps = [1, 2, 2.5, 5, 10]*. """ def __init__(self): """ To know the values of the non-public parameters, please have a look to the defaults of `~matplotlib.ticker.MaxNLocator`. """ if rcParams['_internal.classic_mode']: nbins = 9 steps = [1, 2, 5, 10] else: nbins = 'auto' steps = [1, 2, 2.5, 5, 10] MaxNLocator.__init__(self, nbins=nbins, steps=steps) class AutoMinorLocator(Locator): """ Dynamically find minor tick positions based on the positions of major ticks. The scale must be linear with major ticks evenly spaced. """ def __init__(self, n=None): """ *n* is the number of subdivisions of the interval between major ticks; e.g., n=2 will place a single minor tick midway between major ticks. If *n* is omitted or None, it will be set to 5 or 4. """ self.ndivs = n def __call__(self): 'Return the locations of the ticks' if self.axis.get_scale() == 'log': warnings.warn('AutoMinorLocator does not work with logarithmic ' 'scale') return [] majorlocs = self.axis.get_majorticklocs() try: majorstep = majorlocs[1] - majorlocs[0] except IndexError: # Need at least two major ticks to find minor tick locations # TODO: Figure out a way to still be able to display minor # ticks without two major ticks visible. For now, just display # no ticks at all. return [] if self.ndivs is None: x = int(np.round(10 ** (np.log10(majorstep) % 1))) if x in [1, 5, 10]: ndivs = 5 else: ndivs = 4 else: ndivs = self.ndivs minorstep = majorstep / ndivs vmin, vmax = self.axis.get_view_interval() if vmin > vmax: vmin, vmax = vmax, vmin t0 = majorlocs[0] tmin = ((vmin - t0) // minorstep + 1) * minorstep tmax = ((vmax - t0) // minorstep + 1) * minorstep locs = np.arange(tmin, tmax, minorstep) + t0 cond = np.abs((locs - t0) % majorstep) > minorstep / 10.0 locs = locs.compress(cond) return self.raise_if_exceeds(np.array(locs)) def tick_values(self, vmin, vmax): raise NotImplementedError('Cannot get tick locations for a ' '%s type.' % type(self)) class OldAutoLocator(Locator): """ On autoscale this class picks the best MultipleLocator to set the view limits and the tick locs. """ def __init__(self): self._locator = LinearLocator() def __call__(self): 'Return the locations of the ticks' self.refresh() return self.raise_if_exceeds(self._locator()) def tick_values(self, vmin, vmax): raise NotImplementedError('Cannot get tick locations for a ' '%s type.' % type(self)) def refresh(self): 'refresh internal information based on current lim' vmin, vmax = self.axis.get_view_interval() vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05) d = abs(vmax - vmin) self._locator = self.get_locator(d) def view_limits(self, vmin, vmax): 'Try to choose the view limits intelligently' d = abs(vmax - vmin) self._locator = self.get_locator(d) return self._locator.view_limits(vmin, vmax) def get_locator(self, d): 'pick the best locator based on a distance' d = abs(d) if d <= 0: locator = MultipleLocator(0.2) else: try: ld = math.log10(d) except OverflowError: raise RuntimeError('AutoLocator illegal data interval range') fld = math.floor(ld) base = 10 ** fld #if ld==fld: base = 10**(fld-1) #else: base = 10**fld if d >= 5 * base: ticksize = base elif d >= 2 * base: ticksize = base / 2.0 else: ticksize = base / 5.0 locator = MultipleLocator(ticksize) return locator
86,246
31.94385
79
py