Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/16.input_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/16.input_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/23.post_attention_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/23.post_attention_layernorm.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/dateutil/__pycache__/_common.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/__pycache__/_version.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/__pycache__/easter.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/__pycache__/rrule.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/__pycache__/utils.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/parser/__init__.py +61 -0
- venv/lib/python3.10/site-packages/dateutil/parser/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/parser/__pycache__/_parser.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/parser/__pycache__/isoparser.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/parser/_parser.py +1613 -0
- venv/lib/python3.10/site-packages/dateutil/parser/isoparser.py +416 -0
- venv/lib/python3.10/site-packages/dateutil/rrule.py +1737 -0
- venv/lib/python3.10/site-packages/dateutil/tz/__init__.py +12 -0
- venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/_common.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/_factories.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/tz.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/win.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/dateutil/tz/_common.py +419 -0
- venv/lib/python3.10/site-packages/dateutil/tz/_factories.py +80 -0
- venv/lib/python3.10/site-packages/dateutil/tz/tz.py +1849 -0
- venv/lib/python3.10/site-packages/dateutil/tz/win.py +370 -0
- venv/lib/python3.10/site-packages/dateutil/zoneinfo/__init__.py +167 -0
- venv/lib/python3.10/site-packages/dateutil/zoneinfo/rebuild.py +75 -0
- venv/lib/python3.10/site-packages/mpmath/__init__.py +468 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_base.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_fp.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_iv.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp_python.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/function_docs.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/identification.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/math2.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/rational.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/usertools.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/__pycache__/visualization.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/mpmath/ctx_base.py +494 -0
- venv/lib/python3.10/site-packages/mpmath/ctx_fp.py +253 -0
- venv/lib/python3.10/site-packages/mpmath/ctx_iv.py +551 -0
- venv/lib/python3.10/site-packages/mpmath/ctx_mp.py +1339 -0
- venv/lib/python3.10/site-packages/mpmath/ctx_mp_python.py +1149 -0
- venv/lib/python3.10/site-packages/mpmath/function_docs.py +0 -0
- venv/lib/python3.10/site-packages/mpmath/identification.py +844 -0
- venv/lib/python3.10/site-packages/mpmath/math2.py +672 -0
- venv/lib/python3.10/site-packages/mpmath/rational.py +240 -0
ckpts/universal/global_step80/zero/16.input_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d8908d908572983bfe3012bedb8296fcb975655c3d0958f8fde7f62489e0be8c
|
3 |
+
size 9387
|
ckpts/universal/global_step80/zero/16.input_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b5ef33f459096f81adb8206644c4f87b64d4125edcfe263d16c3406a50bb38dc
|
3 |
+
size 9293
|
ckpts/universal/global_step80/zero/23.post_attention_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bb22c183d6cbf7a28d01769f44a4d76c2739116484847602497e21cee5dacb35
|
3 |
+
size 9372
|
ckpts/universal/global_step80/zero/23.post_attention_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5d7e6c04009d0d429bed6f76978d2504e6085c428ca207c0618c2c0e1f9138ec
|
3 |
+
size 9293
|
venv/lib/python3.10/site-packages/dateutil/__pycache__/_common.cpython-310.pyc
ADDED
Binary file (1.42 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/__pycache__/_version.cpython-310.pyc
ADDED
Binary file (277 Bytes). View file
|
|
venv/lib/python3.10/site-packages/dateutil/__pycache__/easter.cpython-310.pyc
ADDED
Binary file (2.21 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/__pycache__/rrule.cpython-310.pyc
ADDED
Binary file (43.3 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (2.26 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/parser/__init__.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
from ._parser import parse, parser, parserinfo, ParserError
|
3 |
+
from ._parser import DEFAULTPARSER, DEFAULTTZPARSER
|
4 |
+
from ._parser import UnknownTimezoneWarning
|
5 |
+
|
6 |
+
from ._parser import __doc__
|
7 |
+
|
8 |
+
from .isoparser import isoparser, isoparse
|
9 |
+
|
10 |
+
__all__ = ['parse', 'parser', 'parserinfo',
|
11 |
+
'isoparse', 'isoparser',
|
12 |
+
'ParserError',
|
13 |
+
'UnknownTimezoneWarning']
|
14 |
+
|
15 |
+
|
16 |
+
###
|
17 |
+
# Deprecate portions of the private interface so that downstream code that
|
18 |
+
# is improperly relying on it is given *some* notice.
|
19 |
+
|
20 |
+
|
21 |
+
def __deprecated_private_func(f):
|
22 |
+
from functools import wraps
|
23 |
+
import warnings
|
24 |
+
|
25 |
+
msg = ('{name} is a private function and may break without warning, '
|
26 |
+
'it will be moved and or renamed in future versions.')
|
27 |
+
msg = msg.format(name=f.__name__)
|
28 |
+
|
29 |
+
@wraps(f)
|
30 |
+
def deprecated_func(*args, **kwargs):
|
31 |
+
warnings.warn(msg, DeprecationWarning)
|
32 |
+
return f(*args, **kwargs)
|
33 |
+
|
34 |
+
return deprecated_func
|
35 |
+
|
36 |
+
def __deprecate_private_class(c):
|
37 |
+
import warnings
|
38 |
+
|
39 |
+
msg = ('{name} is a private class and may break without warning, '
|
40 |
+
'it will be moved and or renamed in future versions.')
|
41 |
+
msg = msg.format(name=c.__name__)
|
42 |
+
|
43 |
+
class private_class(c):
|
44 |
+
__doc__ = c.__doc__
|
45 |
+
|
46 |
+
def __init__(self, *args, **kwargs):
|
47 |
+
warnings.warn(msg, DeprecationWarning)
|
48 |
+
super(private_class, self).__init__(*args, **kwargs)
|
49 |
+
|
50 |
+
private_class.__name__ = c.__name__
|
51 |
+
|
52 |
+
return private_class
|
53 |
+
|
54 |
+
|
55 |
+
from ._parser import _timelex, _resultbase
|
56 |
+
from ._parser import _tzparser, _parsetz
|
57 |
+
|
58 |
+
_timelex = __deprecate_private_class(_timelex)
|
59 |
+
_tzparser = __deprecate_private_class(_tzparser)
|
60 |
+
_resultbase = __deprecate_private_class(_resultbase)
|
61 |
+
_parsetz = __deprecated_private_func(_parsetz)
|
venv/lib/python3.10/site-packages/dateutil/parser/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (2.07 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/parser/__pycache__/_parser.cpython-310.pyc
ADDED
Binary file (40.5 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/parser/__pycache__/isoparser.cpython-310.pyc
ADDED
Binary file (11.3 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/parser/_parser.py
ADDED
@@ -0,0 +1,1613 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
This module offers a generic date/time string parser which is able to parse
|
4 |
+
most known formats to represent a date and/or time.
|
5 |
+
|
6 |
+
This module attempts to be forgiving with regards to unlikely input formats,
|
7 |
+
returning a datetime object even for dates which are ambiguous. If an element
|
8 |
+
of a date/time stamp is omitted, the following rules are applied:
|
9 |
+
|
10 |
+
- If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour
|
11 |
+
on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is
|
12 |
+
specified.
|
13 |
+
- If a time zone is omitted, a timezone-naive datetime is returned.
|
14 |
+
|
15 |
+
If any other elements are missing, they are taken from the
|
16 |
+
:class:`datetime.datetime` object passed to the parameter ``default``. If this
|
17 |
+
results in a day number exceeding the valid number of days per month, the
|
18 |
+
value falls back to the end of the month.
|
19 |
+
|
20 |
+
Additional resources about date/time string formats can be found below:
|
21 |
+
|
22 |
+
- `A summary of the international standard date and time notation
|
23 |
+
<https://www.cl.cam.ac.uk/~mgk25/iso-time.html>`_
|
24 |
+
- `W3C Date and Time Formats <https://www.w3.org/TR/NOTE-datetime>`_
|
25 |
+
- `Time Formats (Planetary Rings Node) <https://pds-rings.seti.org:443/tools/time_formats.html>`_
|
26 |
+
- `CPAN ParseDate module
|
27 |
+
<https://metacpan.org/pod/release/MUIR/Time-modules-2013.0912/lib/Time/ParseDate.pm>`_
|
28 |
+
- `Java SimpleDateFormat Class
|
29 |
+
<https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html>`_
|
30 |
+
"""
|
31 |
+
from __future__ import unicode_literals
|
32 |
+
|
33 |
+
import datetime
|
34 |
+
import re
|
35 |
+
import string
|
36 |
+
import time
|
37 |
+
import warnings
|
38 |
+
|
39 |
+
from calendar import monthrange
|
40 |
+
from io import StringIO
|
41 |
+
|
42 |
+
import six
|
43 |
+
from six import integer_types, text_type
|
44 |
+
|
45 |
+
from decimal import Decimal
|
46 |
+
|
47 |
+
from warnings import warn
|
48 |
+
|
49 |
+
from .. import relativedelta
|
50 |
+
from .. import tz
|
51 |
+
|
52 |
+
__all__ = ["parse", "parserinfo", "ParserError"]
|
53 |
+
|
54 |
+
|
55 |
+
# TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth
|
56 |
+
# making public and/or figuring out if there is something we can
|
57 |
+
# take off their plate.
|
58 |
+
class _timelex(object):
|
59 |
+
# Fractional seconds are sometimes split by a comma
|
60 |
+
_split_decimal = re.compile("([.,])")
|
61 |
+
|
62 |
+
def __init__(self, instream):
|
63 |
+
if isinstance(instream, (bytes, bytearray)):
|
64 |
+
instream = instream.decode()
|
65 |
+
|
66 |
+
if isinstance(instream, text_type):
|
67 |
+
instream = StringIO(instream)
|
68 |
+
elif getattr(instream, 'read', None) is None:
|
69 |
+
raise TypeError('Parser must be a string or character stream, not '
|
70 |
+
'{itype}'.format(itype=instream.__class__.__name__))
|
71 |
+
|
72 |
+
self.instream = instream
|
73 |
+
self.charstack = []
|
74 |
+
self.tokenstack = []
|
75 |
+
self.eof = False
|
76 |
+
|
77 |
+
def get_token(self):
|
78 |
+
"""
|
79 |
+
This function breaks the time string into lexical units (tokens), which
|
80 |
+
can be parsed by the parser. Lexical units are demarcated by changes in
|
81 |
+
the character set, so any continuous string of letters is considered
|
82 |
+
one unit, any continuous string of numbers is considered one unit.
|
83 |
+
|
84 |
+
The main complication arises from the fact that dots ('.') can be used
|
85 |
+
both as separators (e.g. "Sep.20.2009") or decimal points (e.g.
|
86 |
+
"4:30:21.447"). As such, it is necessary to read the full context of
|
87 |
+
any dot-separated strings before breaking it into tokens; as such, this
|
88 |
+
function maintains a "token stack", for when the ambiguous context
|
89 |
+
demands that multiple tokens be parsed at once.
|
90 |
+
"""
|
91 |
+
if self.tokenstack:
|
92 |
+
return self.tokenstack.pop(0)
|
93 |
+
|
94 |
+
seenletters = False
|
95 |
+
token = None
|
96 |
+
state = None
|
97 |
+
|
98 |
+
while not self.eof:
|
99 |
+
# We only realize that we've reached the end of a token when we
|
100 |
+
# find a character that's not part of the current token - since
|
101 |
+
# that character may be part of the next token, it's stored in the
|
102 |
+
# charstack.
|
103 |
+
if self.charstack:
|
104 |
+
nextchar = self.charstack.pop(0)
|
105 |
+
else:
|
106 |
+
nextchar = self.instream.read(1)
|
107 |
+
while nextchar == '\x00':
|
108 |
+
nextchar = self.instream.read(1)
|
109 |
+
|
110 |
+
if not nextchar:
|
111 |
+
self.eof = True
|
112 |
+
break
|
113 |
+
elif not state:
|
114 |
+
# First character of the token - determines if we're starting
|
115 |
+
# to parse a word, a number or something else.
|
116 |
+
token = nextchar
|
117 |
+
if self.isword(nextchar):
|
118 |
+
state = 'a'
|
119 |
+
elif self.isnum(nextchar):
|
120 |
+
state = '0'
|
121 |
+
elif self.isspace(nextchar):
|
122 |
+
token = ' '
|
123 |
+
break # emit token
|
124 |
+
else:
|
125 |
+
break # emit token
|
126 |
+
elif state == 'a':
|
127 |
+
# If we've already started reading a word, we keep reading
|
128 |
+
# letters until we find something that's not part of a word.
|
129 |
+
seenletters = True
|
130 |
+
if self.isword(nextchar):
|
131 |
+
token += nextchar
|
132 |
+
elif nextchar == '.':
|
133 |
+
token += nextchar
|
134 |
+
state = 'a.'
|
135 |
+
else:
|
136 |
+
self.charstack.append(nextchar)
|
137 |
+
break # emit token
|
138 |
+
elif state == '0':
|
139 |
+
# If we've already started reading a number, we keep reading
|
140 |
+
# numbers until we find something that doesn't fit.
|
141 |
+
if self.isnum(nextchar):
|
142 |
+
token += nextchar
|
143 |
+
elif nextchar == '.' or (nextchar == ',' and len(token) >= 2):
|
144 |
+
token += nextchar
|
145 |
+
state = '0.'
|
146 |
+
else:
|
147 |
+
self.charstack.append(nextchar)
|
148 |
+
break # emit token
|
149 |
+
elif state == 'a.':
|
150 |
+
# If we've seen some letters and a dot separator, continue
|
151 |
+
# parsing, and the tokens will be broken up later.
|
152 |
+
seenletters = True
|
153 |
+
if nextchar == '.' or self.isword(nextchar):
|
154 |
+
token += nextchar
|
155 |
+
elif self.isnum(nextchar) and token[-1] == '.':
|
156 |
+
token += nextchar
|
157 |
+
state = '0.'
|
158 |
+
else:
|
159 |
+
self.charstack.append(nextchar)
|
160 |
+
break # emit token
|
161 |
+
elif state == '0.':
|
162 |
+
# If we've seen at least one dot separator, keep going, we'll
|
163 |
+
# break up the tokens later.
|
164 |
+
if nextchar == '.' or self.isnum(nextchar):
|
165 |
+
token += nextchar
|
166 |
+
elif self.isword(nextchar) and token[-1] == '.':
|
167 |
+
token += nextchar
|
168 |
+
state = 'a.'
|
169 |
+
else:
|
170 |
+
self.charstack.append(nextchar)
|
171 |
+
break # emit token
|
172 |
+
|
173 |
+
if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or
|
174 |
+
token[-1] in '.,')):
|
175 |
+
l = self._split_decimal.split(token)
|
176 |
+
token = l[0]
|
177 |
+
for tok in l[1:]:
|
178 |
+
if tok:
|
179 |
+
self.tokenstack.append(tok)
|
180 |
+
|
181 |
+
if state == '0.' and token.count('.') == 0:
|
182 |
+
token = token.replace(',', '.')
|
183 |
+
|
184 |
+
return token
|
185 |
+
|
186 |
+
def __iter__(self):
|
187 |
+
return self
|
188 |
+
|
189 |
+
def __next__(self):
|
190 |
+
token = self.get_token()
|
191 |
+
if token is None:
|
192 |
+
raise StopIteration
|
193 |
+
|
194 |
+
return token
|
195 |
+
|
196 |
+
def next(self):
|
197 |
+
return self.__next__() # Python 2.x support
|
198 |
+
|
199 |
+
@classmethod
|
200 |
+
def split(cls, s):
|
201 |
+
return list(cls(s))
|
202 |
+
|
203 |
+
@classmethod
|
204 |
+
def isword(cls, nextchar):
|
205 |
+
""" Whether or not the next character is part of a word """
|
206 |
+
return nextchar.isalpha()
|
207 |
+
|
208 |
+
@classmethod
|
209 |
+
def isnum(cls, nextchar):
|
210 |
+
""" Whether the next character is part of a number """
|
211 |
+
return nextchar.isdigit()
|
212 |
+
|
213 |
+
@classmethod
|
214 |
+
def isspace(cls, nextchar):
|
215 |
+
""" Whether the next character is whitespace """
|
216 |
+
return nextchar.isspace()
|
217 |
+
|
218 |
+
|
219 |
+
class _resultbase(object):
|
220 |
+
|
221 |
+
def __init__(self):
|
222 |
+
for attr in self.__slots__:
|
223 |
+
setattr(self, attr, None)
|
224 |
+
|
225 |
+
def _repr(self, classname):
|
226 |
+
l = []
|
227 |
+
for attr in self.__slots__:
|
228 |
+
value = getattr(self, attr)
|
229 |
+
if value is not None:
|
230 |
+
l.append("%s=%s" % (attr, repr(value)))
|
231 |
+
return "%s(%s)" % (classname, ", ".join(l))
|
232 |
+
|
233 |
+
def __len__(self):
|
234 |
+
return (sum(getattr(self, attr) is not None
|
235 |
+
for attr in self.__slots__))
|
236 |
+
|
237 |
+
def __repr__(self):
|
238 |
+
return self._repr(self.__class__.__name__)
|
239 |
+
|
240 |
+
|
241 |
+
class parserinfo(object):
|
242 |
+
"""
|
243 |
+
Class which handles what inputs are accepted. Subclass this to customize
|
244 |
+
the language and acceptable values for each parameter.
|
245 |
+
|
246 |
+
:param dayfirst:
|
247 |
+
Whether to interpret the first value in an ambiguous 3-integer date
|
248 |
+
(e.g. 01/05/09) as the day (``True``) or month (``False``). If
|
249 |
+
``yearfirst`` is set to ``True``, this distinguishes between YDM
|
250 |
+
and YMD. Default is ``False``.
|
251 |
+
|
252 |
+
:param yearfirst:
|
253 |
+
Whether to interpret the first value in an ambiguous 3-integer date
|
254 |
+
(e.g. 01/05/09) as the year. If ``True``, the first number is taken
|
255 |
+
to be the year, otherwise the last number is taken to be the year.
|
256 |
+
Default is ``False``.
|
257 |
+
"""
|
258 |
+
|
259 |
+
# m from a.m/p.m, t from ISO T separator
|
260 |
+
JUMP = [" ", ".", ",", ";", "-", "/", "'",
|
261 |
+
"at", "on", "and", "ad", "m", "t", "of",
|
262 |
+
"st", "nd", "rd", "th"]
|
263 |
+
|
264 |
+
WEEKDAYS = [("Mon", "Monday"),
|
265 |
+
("Tue", "Tuesday"), # TODO: "Tues"
|
266 |
+
("Wed", "Wednesday"),
|
267 |
+
("Thu", "Thursday"), # TODO: "Thurs"
|
268 |
+
("Fri", "Friday"),
|
269 |
+
("Sat", "Saturday"),
|
270 |
+
("Sun", "Sunday")]
|
271 |
+
MONTHS = [("Jan", "January"),
|
272 |
+
("Feb", "February"), # TODO: "Febr"
|
273 |
+
("Mar", "March"),
|
274 |
+
("Apr", "April"),
|
275 |
+
("May", "May"),
|
276 |
+
("Jun", "June"),
|
277 |
+
("Jul", "July"),
|
278 |
+
("Aug", "August"),
|
279 |
+
("Sep", "Sept", "September"),
|
280 |
+
("Oct", "October"),
|
281 |
+
("Nov", "November"),
|
282 |
+
("Dec", "December")]
|
283 |
+
HMS = [("h", "hour", "hours"),
|
284 |
+
("m", "minute", "minutes"),
|
285 |
+
("s", "second", "seconds")]
|
286 |
+
AMPM = [("am", "a"),
|
287 |
+
("pm", "p")]
|
288 |
+
UTCZONE = ["UTC", "GMT", "Z", "z"]
|
289 |
+
PERTAIN = ["of"]
|
290 |
+
TZOFFSET = {}
|
291 |
+
# TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate",
|
292 |
+
# "Anno Domini", "Year of Our Lord"]
|
293 |
+
|
294 |
+
def __init__(self, dayfirst=False, yearfirst=False):
|
295 |
+
self._jump = self._convert(self.JUMP)
|
296 |
+
self._weekdays = self._convert(self.WEEKDAYS)
|
297 |
+
self._months = self._convert(self.MONTHS)
|
298 |
+
self._hms = self._convert(self.HMS)
|
299 |
+
self._ampm = self._convert(self.AMPM)
|
300 |
+
self._utczone = self._convert(self.UTCZONE)
|
301 |
+
self._pertain = self._convert(self.PERTAIN)
|
302 |
+
|
303 |
+
self.dayfirst = dayfirst
|
304 |
+
self.yearfirst = yearfirst
|
305 |
+
|
306 |
+
self._year = time.localtime().tm_year
|
307 |
+
self._century = self._year // 100 * 100
|
308 |
+
|
309 |
+
def _convert(self, lst):
|
310 |
+
dct = {}
|
311 |
+
for i, v in enumerate(lst):
|
312 |
+
if isinstance(v, tuple):
|
313 |
+
for v in v:
|
314 |
+
dct[v.lower()] = i
|
315 |
+
else:
|
316 |
+
dct[v.lower()] = i
|
317 |
+
return dct
|
318 |
+
|
319 |
+
def jump(self, name):
|
320 |
+
return name.lower() in self._jump
|
321 |
+
|
322 |
+
def weekday(self, name):
|
323 |
+
try:
|
324 |
+
return self._weekdays[name.lower()]
|
325 |
+
except KeyError:
|
326 |
+
pass
|
327 |
+
return None
|
328 |
+
|
329 |
+
def month(self, name):
|
330 |
+
try:
|
331 |
+
return self._months[name.lower()] + 1
|
332 |
+
except KeyError:
|
333 |
+
pass
|
334 |
+
return None
|
335 |
+
|
336 |
+
def hms(self, name):
|
337 |
+
try:
|
338 |
+
return self._hms[name.lower()]
|
339 |
+
except KeyError:
|
340 |
+
return None
|
341 |
+
|
342 |
+
def ampm(self, name):
|
343 |
+
try:
|
344 |
+
return self._ampm[name.lower()]
|
345 |
+
except KeyError:
|
346 |
+
return None
|
347 |
+
|
348 |
+
def pertain(self, name):
|
349 |
+
return name.lower() in self._pertain
|
350 |
+
|
351 |
+
def utczone(self, name):
|
352 |
+
return name.lower() in self._utczone
|
353 |
+
|
354 |
+
def tzoffset(self, name):
|
355 |
+
if name in self._utczone:
|
356 |
+
return 0
|
357 |
+
|
358 |
+
return self.TZOFFSET.get(name)
|
359 |
+
|
360 |
+
def convertyear(self, year, century_specified=False):
|
361 |
+
"""
|
362 |
+
Converts two-digit years to year within [-50, 49]
|
363 |
+
range of self._year (current local time)
|
364 |
+
"""
|
365 |
+
|
366 |
+
# Function contract is that the year is always positive
|
367 |
+
assert year >= 0
|
368 |
+
|
369 |
+
if year < 100 and not century_specified:
|
370 |
+
# assume current century to start
|
371 |
+
year += self._century
|
372 |
+
|
373 |
+
if year >= self._year + 50: # if too far in future
|
374 |
+
year -= 100
|
375 |
+
elif year < self._year - 50: # if too far in past
|
376 |
+
year += 100
|
377 |
+
|
378 |
+
return year
|
379 |
+
|
380 |
+
def validate(self, res):
|
381 |
+
# move to info
|
382 |
+
if res.year is not None:
|
383 |
+
res.year = self.convertyear(res.year, res.century_specified)
|
384 |
+
|
385 |
+
if ((res.tzoffset == 0 and not res.tzname) or
|
386 |
+
(res.tzname == 'Z' or res.tzname == 'z')):
|
387 |
+
res.tzname = "UTC"
|
388 |
+
res.tzoffset = 0
|
389 |
+
elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname):
|
390 |
+
res.tzoffset = 0
|
391 |
+
return True
|
392 |
+
|
393 |
+
|
394 |
+
class _ymd(list):
|
395 |
+
def __init__(self, *args, **kwargs):
|
396 |
+
super(self.__class__, self).__init__(*args, **kwargs)
|
397 |
+
self.century_specified = False
|
398 |
+
self.dstridx = None
|
399 |
+
self.mstridx = None
|
400 |
+
self.ystridx = None
|
401 |
+
|
402 |
+
@property
|
403 |
+
def has_year(self):
|
404 |
+
return self.ystridx is not None
|
405 |
+
|
406 |
+
@property
|
407 |
+
def has_month(self):
|
408 |
+
return self.mstridx is not None
|
409 |
+
|
410 |
+
@property
|
411 |
+
def has_day(self):
|
412 |
+
return self.dstridx is not None
|
413 |
+
|
414 |
+
def could_be_day(self, value):
|
415 |
+
if self.has_day:
|
416 |
+
return False
|
417 |
+
elif not self.has_month:
|
418 |
+
return 1 <= value <= 31
|
419 |
+
elif not self.has_year:
|
420 |
+
# Be permissive, assume leap year
|
421 |
+
month = self[self.mstridx]
|
422 |
+
return 1 <= value <= monthrange(2000, month)[1]
|
423 |
+
else:
|
424 |
+
month = self[self.mstridx]
|
425 |
+
year = self[self.ystridx]
|
426 |
+
return 1 <= value <= monthrange(year, month)[1]
|
427 |
+
|
428 |
+
def append(self, val, label=None):
|
429 |
+
if hasattr(val, '__len__'):
|
430 |
+
if val.isdigit() and len(val) > 2:
|
431 |
+
self.century_specified = True
|
432 |
+
if label not in [None, 'Y']: # pragma: no cover
|
433 |
+
raise ValueError(label)
|
434 |
+
label = 'Y'
|
435 |
+
elif val > 100:
|
436 |
+
self.century_specified = True
|
437 |
+
if label not in [None, 'Y']: # pragma: no cover
|
438 |
+
raise ValueError(label)
|
439 |
+
label = 'Y'
|
440 |
+
|
441 |
+
super(self.__class__, self).append(int(val))
|
442 |
+
|
443 |
+
if label == 'M':
|
444 |
+
if self.has_month:
|
445 |
+
raise ValueError('Month is already set')
|
446 |
+
self.mstridx = len(self) - 1
|
447 |
+
elif label == 'D':
|
448 |
+
if self.has_day:
|
449 |
+
raise ValueError('Day is already set')
|
450 |
+
self.dstridx = len(self) - 1
|
451 |
+
elif label == 'Y':
|
452 |
+
if self.has_year:
|
453 |
+
raise ValueError('Year is already set')
|
454 |
+
self.ystridx = len(self) - 1
|
455 |
+
|
456 |
+
def _resolve_from_stridxs(self, strids):
|
457 |
+
"""
|
458 |
+
Try to resolve the identities of year/month/day elements using
|
459 |
+
ystridx, mstridx, and dstridx, if enough of these are specified.
|
460 |
+
"""
|
461 |
+
if len(self) == 3 and len(strids) == 2:
|
462 |
+
# we can back out the remaining stridx value
|
463 |
+
missing = [x for x in range(3) if x not in strids.values()]
|
464 |
+
key = [x for x in ['y', 'm', 'd'] if x not in strids]
|
465 |
+
assert len(missing) == len(key) == 1
|
466 |
+
key = key[0]
|
467 |
+
val = missing[0]
|
468 |
+
strids[key] = val
|
469 |
+
|
470 |
+
assert len(self) == len(strids) # otherwise this should not be called
|
471 |
+
out = {key: self[strids[key]] for key in strids}
|
472 |
+
return (out.get('y'), out.get('m'), out.get('d'))
|
473 |
+
|
474 |
+
def resolve_ymd(self, yearfirst, dayfirst):
|
475 |
+
len_ymd = len(self)
|
476 |
+
year, month, day = (None, None, None)
|
477 |
+
|
478 |
+
strids = (('y', self.ystridx),
|
479 |
+
('m', self.mstridx),
|
480 |
+
('d', self.dstridx))
|
481 |
+
|
482 |
+
strids = {key: val for key, val in strids if val is not None}
|
483 |
+
if (len(self) == len(strids) > 0 or
|
484 |
+
(len(self) == 3 and len(strids) == 2)):
|
485 |
+
return self._resolve_from_stridxs(strids)
|
486 |
+
|
487 |
+
mstridx = self.mstridx
|
488 |
+
|
489 |
+
if len_ymd > 3:
|
490 |
+
raise ValueError("More than three YMD values")
|
491 |
+
elif len_ymd == 1 or (mstridx is not None and len_ymd == 2):
|
492 |
+
# One member, or two members with a month string
|
493 |
+
if mstridx is not None:
|
494 |
+
month = self[mstridx]
|
495 |
+
# since mstridx is 0 or 1, self[mstridx-1] always
|
496 |
+
# looks up the other element
|
497 |
+
other = self[mstridx - 1]
|
498 |
+
else:
|
499 |
+
other = self[0]
|
500 |
+
|
501 |
+
if len_ymd > 1 or mstridx is None:
|
502 |
+
if other > 31:
|
503 |
+
year = other
|
504 |
+
else:
|
505 |
+
day = other
|
506 |
+
|
507 |
+
elif len_ymd == 2:
|
508 |
+
# Two members with numbers
|
509 |
+
if self[0] > 31:
|
510 |
+
# 99-01
|
511 |
+
year, month = self
|
512 |
+
elif self[1] > 31:
|
513 |
+
# 01-99
|
514 |
+
month, year = self
|
515 |
+
elif dayfirst and self[1] <= 12:
|
516 |
+
# 13-01
|
517 |
+
day, month = self
|
518 |
+
else:
|
519 |
+
# 01-13
|
520 |
+
month, day = self
|
521 |
+
|
522 |
+
elif len_ymd == 3:
|
523 |
+
# Three members
|
524 |
+
if mstridx == 0:
|
525 |
+
if self[1] > 31:
|
526 |
+
# Apr-2003-25
|
527 |
+
month, year, day = self
|
528 |
+
else:
|
529 |
+
month, day, year = self
|
530 |
+
elif mstridx == 1:
|
531 |
+
if self[0] > 31 or (yearfirst and self[2] <= 31):
|
532 |
+
# 99-Jan-01
|
533 |
+
year, month, day = self
|
534 |
+
else:
|
535 |
+
# 01-Jan-01
|
536 |
+
# Give precedence to day-first, since
|
537 |
+
# two-digit years is usually hand-written.
|
538 |
+
day, month, year = self
|
539 |
+
|
540 |
+
elif mstridx == 2:
|
541 |
+
# WTF!?
|
542 |
+
if self[1] > 31:
|
543 |
+
# 01-99-Jan
|
544 |
+
day, year, month = self
|
545 |
+
else:
|
546 |
+
# 99-01-Jan
|
547 |
+
year, day, month = self
|
548 |
+
|
549 |
+
else:
|
550 |
+
if (self[0] > 31 or
|
551 |
+
self.ystridx == 0 or
|
552 |
+
(yearfirst and self[1] <= 12 and self[2] <= 31)):
|
553 |
+
# 99-01-01
|
554 |
+
if dayfirst and self[2] <= 12:
|
555 |
+
year, day, month = self
|
556 |
+
else:
|
557 |
+
year, month, day = self
|
558 |
+
elif self[0] > 12 or (dayfirst and self[1] <= 12):
|
559 |
+
# 13-01-01
|
560 |
+
day, month, year = self
|
561 |
+
else:
|
562 |
+
# 01-13-01
|
563 |
+
month, day, year = self
|
564 |
+
|
565 |
+
return year, month, day
|
566 |
+
|
567 |
+
|
568 |
+
class parser(object):
|
569 |
+
def __init__(self, info=None):
|
570 |
+
self.info = info or parserinfo()
|
571 |
+
|
572 |
+
def parse(self, timestr, default=None,
|
573 |
+
ignoretz=False, tzinfos=None, **kwargs):
|
574 |
+
"""
|
575 |
+
Parse the date/time string into a :class:`datetime.datetime` object.
|
576 |
+
|
577 |
+
:param timestr:
|
578 |
+
Any date/time string using the supported formats.
|
579 |
+
|
580 |
+
:param default:
|
581 |
+
The default datetime object, if this is a datetime object and not
|
582 |
+
``None``, elements specified in ``timestr`` replace elements in the
|
583 |
+
default object.
|
584 |
+
|
585 |
+
:param ignoretz:
|
586 |
+
If set ``True``, time zones in parsed strings are ignored and a
|
587 |
+
naive :class:`datetime.datetime` object is returned.
|
588 |
+
|
589 |
+
:param tzinfos:
|
590 |
+
Additional time zone names / aliases which may be present in the
|
591 |
+
string. This argument maps time zone names (and optionally offsets
|
592 |
+
from those time zones) to time zones. This parameter can be a
|
593 |
+
dictionary with timezone aliases mapping time zone names to time
|
594 |
+
zones or a function taking two parameters (``tzname`` and
|
595 |
+
``tzoffset``) and returning a time zone.
|
596 |
+
|
597 |
+
The timezones to which the names are mapped can be an integer
|
598 |
+
offset from UTC in seconds or a :class:`tzinfo` object.
|
599 |
+
|
600 |
+
.. doctest::
|
601 |
+
:options: +NORMALIZE_WHITESPACE
|
602 |
+
|
603 |
+
>>> from dateutil.parser import parse
|
604 |
+
>>> from dateutil.tz import gettz
|
605 |
+
>>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")}
|
606 |
+
>>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos)
|
607 |
+
datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200))
|
608 |
+
>>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos)
|
609 |
+
datetime.datetime(2012, 1, 19, 17, 21,
|
610 |
+
tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago'))
|
611 |
+
|
612 |
+
This parameter is ignored if ``ignoretz`` is set.
|
613 |
+
|
614 |
+
:param \\*\\*kwargs:
|
615 |
+
Keyword arguments as passed to ``_parse()``.
|
616 |
+
|
617 |
+
:return:
|
618 |
+
Returns a :class:`datetime.datetime` object or, if the
|
619 |
+
``fuzzy_with_tokens`` option is ``True``, returns a tuple, the
|
620 |
+
first element being a :class:`datetime.datetime` object, the second
|
621 |
+
a tuple containing the fuzzy tokens.
|
622 |
+
|
623 |
+
:raises ParserError:
|
624 |
+
Raised for invalid or unknown string format, if the provided
|
625 |
+
:class:`tzinfo` is not in a valid format, or if an invalid date
|
626 |
+
would be created.
|
627 |
+
|
628 |
+
:raises TypeError:
|
629 |
+
Raised for non-string or character stream input.
|
630 |
+
|
631 |
+
:raises OverflowError:
|
632 |
+
Raised if the parsed date exceeds the largest valid C integer on
|
633 |
+
your system.
|
634 |
+
"""
|
635 |
+
|
636 |
+
if default is None:
|
637 |
+
default = datetime.datetime.now().replace(hour=0, minute=0,
|
638 |
+
second=0, microsecond=0)
|
639 |
+
|
640 |
+
res, skipped_tokens = self._parse(timestr, **kwargs)
|
641 |
+
|
642 |
+
if res is None:
|
643 |
+
raise ParserError("Unknown string format: %s", timestr)
|
644 |
+
|
645 |
+
if len(res) == 0:
|
646 |
+
raise ParserError("String does not contain a date: %s", timestr)
|
647 |
+
|
648 |
+
try:
|
649 |
+
ret = self._build_naive(res, default)
|
650 |
+
except ValueError as e:
|
651 |
+
six.raise_from(ParserError(str(e) + ": %s", timestr), e)
|
652 |
+
|
653 |
+
if not ignoretz:
|
654 |
+
ret = self._build_tzaware(ret, res, tzinfos)
|
655 |
+
|
656 |
+
if kwargs.get('fuzzy_with_tokens', False):
|
657 |
+
return ret, skipped_tokens
|
658 |
+
else:
|
659 |
+
return ret
|
660 |
+
|
661 |
+
class _result(_resultbase):
|
662 |
+
__slots__ = ["year", "month", "day", "weekday",
|
663 |
+
"hour", "minute", "second", "microsecond",
|
664 |
+
"tzname", "tzoffset", "ampm","any_unused_tokens"]
|
665 |
+
|
666 |
+
def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False,
|
667 |
+
fuzzy_with_tokens=False):
|
668 |
+
"""
|
669 |
+
Private method which performs the heavy lifting of parsing, called from
|
670 |
+
``parse()``, which passes on its ``kwargs`` to this function.
|
671 |
+
|
672 |
+
:param timestr:
|
673 |
+
The string to parse.
|
674 |
+
|
675 |
+
:param dayfirst:
|
676 |
+
Whether to interpret the first value in an ambiguous 3-integer date
|
677 |
+
(e.g. 01/05/09) as the day (``True``) or month (``False``). If
|
678 |
+
``yearfirst`` is set to ``True``, this distinguishes between YDM
|
679 |
+
and YMD. If set to ``None``, this value is retrieved from the
|
680 |
+
current :class:`parserinfo` object (which itself defaults to
|
681 |
+
``False``).
|
682 |
+
|
683 |
+
:param yearfirst:
|
684 |
+
Whether to interpret the first value in an ambiguous 3-integer date
|
685 |
+
(e.g. 01/05/09) as the year. If ``True``, the first number is taken
|
686 |
+
to be the year, otherwise the last number is taken to be the year.
|
687 |
+
If this is set to ``None``, the value is retrieved from the current
|
688 |
+
:class:`parserinfo` object (which itself defaults to ``False``).
|
689 |
+
|
690 |
+
:param fuzzy:
|
691 |
+
Whether to allow fuzzy parsing, allowing for string like "Today is
|
692 |
+
January 1, 2047 at 8:21:00AM".
|
693 |
+
|
694 |
+
:param fuzzy_with_tokens:
|
695 |
+
If ``True``, ``fuzzy`` is automatically set to True, and the parser
|
696 |
+
will return a tuple where the first element is the parsed
|
697 |
+
:class:`datetime.datetime` datetimestamp and the second element is
|
698 |
+
a tuple containing the portions of the string which were ignored:
|
699 |
+
|
700 |
+
.. doctest::
|
701 |
+
|
702 |
+
>>> from dateutil.parser import parse
|
703 |
+
>>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True)
|
704 |
+
(datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))
|
705 |
+
|
706 |
+
"""
|
707 |
+
if fuzzy_with_tokens:
|
708 |
+
fuzzy = True
|
709 |
+
|
710 |
+
info = self.info
|
711 |
+
|
712 |
+
if dayfirst is None:
|
713 |
+
dayfirst = info.dayfirst
|
714 |
+
|
715 |
+
if yearfirst is None:
|
716 |
+
yearfirst = info.yearfirst
|
717 |
+
|
718 |
+
res = self._result()
|
719 |
+
l = _timelex.split(timestr) # Splits the timestr into tokens
|
720 |
+
|
721 |
+
skipped_idxs = []
|
722 |
+
|
723 |
+
# year/month/day list
|
724 |
+
ymd = _ymd()
|
725 |
+
|
726 |
+
len_l = len(l)
|
727 |
+
i = 0
|
728 |
+
try:
|
729 |
+
while i < len_l:
|
730 |
+
|
731 |
+
# Check if it's a number
|
732 |
+
value_repr = l[i]
|
733 |
+
try:
|
734 |
+
value = float(value_repr)
|
735 |
+
except ValueError:
|
736 |
+
value = None
|
737 |
+
|
738 |
+
if value is not None:
|
739 |
+
# Numeric token
|
740 |
+
i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy)
|
741 |
+
|
742 |
+
# Check weekday
|
743 |
+
elif info.weekday(l[i]) is not None:
|
744 |
+
value = info.weekday(l[i])
|
745 |
+
res.weekday = value
|
746 |
+
|
747 |
+
# Check month name
|
748 |
+
elif info.month(l[i]) is not None:
|
749 |
+
value = info.month(l[i])
|
750 |
+
ymd.append(value, 'M')
|
751 |
+
|
752 |
+
if i + 1 < len_l:
|
753 |
+
if l[i + 1] in ('-', '/'):
|
754 |
+
# Jan-01[-99]
|
755 |
+
sep = l[i + 1]
|
756 |
+
ymd.append(l[i + 2])
|
757 |
+
|
758 |
+
if i + 3 < len_l and l[i + 3] == sep:
|
759 |
+
# Jan-01-99
|
760 |
+
ymd.append(l[i + 4])
|
761 |
+
i += 2
|
762 |
+
|
763 |
+
i += 2
|
764 |
+
|
765 |
+
elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and
|
766 |
+
info.pertain(l[i + 2])):
|
767 |
+
# Jan of 01
|
768 |
+
# In this case, 01 is clearly year
|
769 |
+
if l[i + 4].isdigit():
|
770 |
+
# Convert it here to become unambiguous
|
771 |
+
value = int(l[i + 4])
|
772 |
+
year = str(info.convertyear(value))
|
773 |
+
ymd.append(year, 'Y')
|
774 |
+
else:
|
775 |
+
# Wrong guess
|
776 |
+
pass
|
777 |
+
# TODO: not hit in tests
|
778 |
+
i += 4
|
779 |
+
|
780 |
+
# Check am/pm
|
781 |
+
elif info.ampm(l[i]) is not None:
|
782 |
+
value = info.ampm(l[i])
|
783 |
+
val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy)
|
784 |
+
|
785 |
+
if val_is_ampm:
|
786 |
+
res.hour = self._adjust_ampm(res.hour, value)
|
787 |
+
res.ampm = value
|
788 |
+
|
789 |
+
elif fuzzy:
|
790 |
+
skipped_idxs.append(i)
|
791 |
+
|
792 |
+
# Check for a timezone name
|
793 |
+
elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]):
|
794 |
+
res.tzname = l[i]
|
795 |
+
res.tzoffset = info.tzoffset(res.tzname)
|
796 |
+
|
797 |
+
# Check for something like GMT+3, or BRST+3. Notice
|
798 |
+
# that it doesn't mean "I am 3 hours after GMT", but
|
799 |
+
# "my time +3 is GMT". If found, we reverse the
|
800 |
+
# logic so that timezone parsing code will get it
|
801 |
+
# right.
|
802 |
+
if i + 1 < len_l and l[i + 1] in ('+', '-'):
|
803 |
+
l[i + 1] = ('+', '-')[l[i + 1] == '+']
|
804 |
+
res.tzoffset = None
|
805 |
+
if info.utczone(res.tzname):
|
806 |
+
# With something like GMT+3, the timezone
|
807 |
+
# is *not* GMT.
|
808 |
+
res.tzname = None
|
809 |
+
|
810 |
+
# Check for a numbered timezone
|
811 |
+
elif res.hour is not None and l[i] in ('+', '-'):
|
812 |
+
signal = (-1, 1)[l[i] == '+']
|
813 |
+
len_li = len(l[i + 1])
|
814 |
+
|
815 |
+
# TODO: check that l[i + 1] is integer?
|
816 |
+
if len_li == 4:
|
817 |
+
# -0300
|
818 |
+
hour_offset = int(l[i + 1][:2])
|
819 |
+
min_offset = int(l[i + 1][2:])
|
820 |
+
elif i + 2 < len_l and l[i + 2] == ':':
|
821 |
+
# -03:00
|
822 |
+
hour_offset = int(l[i + 1])
|
823 |
+
min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like?
|
824 |
+
i += 2
|
825 |
+
elif len_li <= 2:
|
826 |
+
# -[0]3
|
827 |
+
hour_offset = int(l[i + 1][:2])
|
828 |
+
min_offset = 0
|
829 |
+
else:
|
830 |
+
raise ValueError(timestr)
|
831 |
+
|
832 |
+
res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60)
|
833 |
+
|
834 |
+
# Look for a timezone name between parenthesis
|
835 |
+
if (i + 5 < len_l and
|
836 |
+
info.jump(l[i + 2]) and l[i + 3] == '(' and
|
837 |
+
l[i + 5] == ')' and
|
838 |
+
3 <= len(l[i + 4]) and
|
839 |
+
self._could_be_tzname(res.hour, res.tzname,
|
840 |
+
None, l[i + 4])):
|
841 |
+
# -0300 (BRST)
|
842 |
+
res.tzname = l[i + 4]
|
843 |
+
i += 4
|
844 |
+
|
845 |
+
i += 1
|
846 |
+
|
847 |
+
# Check jumps
|
848 |
+
elif not (info.jump(l[i]) or fuzzy):
|
849 |
+
raise ValueError(timestr)
|
850 |
+
|
851 |
+
else:
|
852 |
+
skipped_idxs.append(i)
|
853 |
+
i += 1
|
854 |
+
|
855 |
+
# Process year/month/day
|
856 |
+
year, month, day = ymd.resolve_ymd(yearfirst, dayfirst)
|
857 |
+
|
858 |
+
res.century_specified = ymd.century_specified
|
859 |
+
res.year = year
|
860 |
+
res.month = month
|
861 |
+
res.day = day
|
862 |
+
|
863 |
+
except (IndexError, ValueError):
|
864 |
+
return None, None
|
865 |
+
|
866 |
+
if not info.validate(res):
|
867 |
+
return None, None
|
868 |
+
|
869 |
+
if fuzzy_with_tokens:
|
870 |
+
skipped_tokens = self._recombine_skipped(l, skipped_idxs)
|
871 |
+
return res, tuple(skipped_tokens)
|
872 |
+
else:
|
873 |
+
return res, None
|
874 |
+
|
875 |
+
def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy):
|
876 |
+
# Token is a number
|
877 |
+
value_repr = tokens[idx]
|
878 |
+
try:
|
879 |
+
value = self._to_decimal(value_repr)
|
880 |
+
except Exception as e:
|
881 |
+
six.raise_from(ValueError('Unknown numeric token'), e)
|
882 |
+
|
883 |
+
len_li = len(value_repr)
|
884 |
+
|
885 |
+
len_l = len(tokens)
|
886 |
+
|
887 |
+
if (len(ymd) == 3 and len_li in (2, 4) and
|
888 |
+
res.hour is None and
|
889 |
+
(idx + 1 >= len_l or
|
890 |
+
(tokens[idx + 1] != ':' and
|
891 |
+
info.hms(tokens[idx + 1]) is None))):
|
892 |
+
# 19990101T23[59]
|
893 |
+
s = tokens[idx]
|
894 |
+
res.hour = int(s[:2])
|
895 |
+
|
896 |
+
if len_li == 4:
|
897 |
+
res.minute = int(s[2:])
|
898 |
+
|
899 |
+
elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6):
|
900 |
+
# YYMMDD or HHMMSS[.ss]
|
901 |
+
s = tokens[idx]
|
902 |
+
|
903 |
+
if not ymd and '.' not in tokens[idx]:
|
904 |
+
ymd.append(s[:2])
|
905 |
+
ymd.append(s[2:4])
|
906 |
+
ymd.append(s[4:])
|
907 |
+
else:
|
908 |
+
# 19990101T235959[.59]
|
909 |
+
|
910 |
+
# TODO: Check if res attributes already set.
|
911 |
+
res.hour = int(s[:2])
|
912 |
+
res.minute = int(s[2:4])
|
913 |
+
res.second, res.microsecond = self._parsems(s[4:])
|
914 |
+
|
915 |
+
elif len_li in (8, 12, 14):
|
916 |
+
# YYYYMMDD
|
917 |
+
s = tokens[idx]
|
918 |
+
ymd.append(s[:4], 'Y')
|
919 |
+
ymd.append(s[4:6])
|
920 |
+
ymd.append(s[6:8])
|
921 |
+
|
922 |
+
if len_li > 8:
|
923 |
+
res.hour = int(s[8:10])
|
924 |
+
res.minute = int(s[10:12])
|
925 |
+
|
926 |
+
if len_li > 12:
|
927 |
+
res.second = int(s[12:])
|
928 |
+
|
929 |
+
elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None:
|
930 |
+
# HH[ ]h or MM[ ]m or SS[.ss][ ]s
|
931 |
+
hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True)
|
932 |
+
(idx, hms) = self._parse_hms(idx, tokens, info, hms_idx)
|
933 |
+
if hms is not None:
|
934 |
+
# TODO: checking that hour/minute/second are not
|
935 |
+
# already set?
|
936 |
+
self._assign_hms(res, value_repr, hms)
|
937 |
+
|
938 |
+
elif idx + 2 < len_l and tokens[idx + 1] == ':':
|
939 |
+
# HH:MM[:SS[.ss]]
|
940 |
+
res.hour = int(value)
|
941 |
+
value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this?
|
942 |
+
(res.minute, res.second) = self._parse_min_sec(value)
|
943 |
+
|
944 |
+
if idx + 4 < len_l and tokens[idx + 3] == ':':
|
945 |
+
res.second, res.microsecond = self._parsems(tokens[idx + 4])
|
946 |
+
|
947 |
+
idx += 2
|
948 |
+
|
949 |
+
idx += 2
|
950 |
+
|
951 |
+
elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'):
|
952 |
+
sep = tokens[idx + 1]
|
953 |
+
ymd.append(value_repr)
|
954 |
+
|
955 |
+
if idx + 2 < len_l and not info.jump(tokens[idx + 2]):
|
956 |
+
if tokens[idx + 2].isdigit():
|
957 |
+
# 01-01[-01]
|
958 |
+
ymd.append(tokens[idx + 2])
|
959 |
+
else:
|
960 |
+
# 01-Jan[-01]
|
961 |
+
value = info.month(tokens[idx + 2])
|
962 |
+
|
963 |
+
if value is not None:
|
964 |
+
ymd.append(value, 'M')
|
965 |
+
else:
|
966 |
+
raise ValueError()
|
967 |
+
|
968 |
+
if idx + 3 < len_l and tokens[idx + 3] == sep:
|
969 |
+
# We have three members
|
970 |
+
value = info.month(tokens[idx + 4])
|
971 |
+
|
972 |
+
if value is not None:
|
973 |
+
ymd.append(value, 'M')
|
974 |
+
else:
|
975 |
+
ymd.append(tokens[idx + 4])
|
976 |
+
idx += 2
|
977 |
+
|
978 |
+
idx += 1
|
979 |
+
idx += 1
|
980 |
+
|
981 |
+
elif idx + 1 >= len_l or info.jump(tokens[idx + 1]):
|
982 |
+
if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None:
|
983 |
+
# 12 am
|
984 |
+
hour = int(value)
|
985 |
+
res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2]))
|
986 |
+
idx += 1
|
987 |
+
else:
|
988 |
+
# Year, month or day
|
989 |
+
ymd.append(value)
|
990 |
+
idx += 1
|
991 |
+
|
992 |
+
elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24):
|
993 |
+
# 12am
|
994 |
+
hour = int(value)
|
995 |
+
res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1]))
|
996 |
+
idx += 1
|
997 |
+
|
998 |
+
elif ymd.could_be_day(value):
|
999 |
+
ymd.append(value)
|
1000 |
+
|
1001 |
+
elif not fuzzy:
|
1002 |
+
raise ValueError()
|
1003 |
+
|
1004 |
+
return idx
|
1005 |
+
|
1006 |
+
def _find_hms_idx(self, idx, tokens, info, allow_jump):
|
1007 |
+
len_l = len(tokens)
|
1008 |
+
|
1009 |
+
if idx+1 < len_l and info.hms(tokens[idx+1]) is not None:
|
1010 |
+
# There is an "h", "m", or "s" label following this token. We take
|
1011 |
+
# assign the upcoming label to the current token.
|
1012 |
+
# e.g. the "12" in 12h"
|
1013 |
+
hms_idx = idx + 1
|
1014 |
+
|
1015 |
+
elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and
|
1016 |
+
info.hms(tokens[idx+2]) is not None):
|
1017 |
+
# There is a space and then an "h", "m", or "s" label.
|
1018 |
+
# e.g. the "12" in "12 h"
|
1019 |
+
hms_idx = idx + 2
|
1020 |
+
|
1021 |
+
elif idx > 0 and info.hms(tokens[idx-1]) is not None:
|
1022 |
+
# There is a "h", "m", or "s" preceding this token. Since neither
|
1023 |
+
# of the previous cases was hit, there is no label following this
|
1024 |
+
# token, so we use the previous label.
|
1025 |
+
# e.g. the "04" in "12h04"
|
1026 |
+
hms_idx = idx-1
|
1027 |
+
|
1028 |
+
elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and
|
1029 |
+
info.hms(tokens[idx-2]) is not None):
|
1030 |
+
# If we are looking at the final token, we allow for a
|
1031 |
+
# backward-looking check to skip over a space.
|
1032 |
+
# TODO: Are we sure this is the right condition here?
|
1033 |
+
hms_idx = idx - 2
|
1034 |
+
|
1035 |
+
else:
|
1036 |
+
hms_idx = None
|
1037 |
+
|
1038 |
+
return hms_idx
|
1039 |
+
|
1040 |
+
def _assign_hms(self, res, value_repr, hms):
|
1041 |
+
# See GH issue #427, fixing float rounding
|
1042 |
+
value = self._to_decimal(value_repr)
|
1043 |
+
|
1044 |
+
if hms == 0:
|
1045 |
+
# Hour
|
1046 |
+
res.hour = int(value)
|
1047 |
+
if value % 1:
|
1048 |
+
res.minute = int(60*(value % 1))
|
1049 |
+
|
1050 |
+
elif hms == 1:
|
1051 |
+
(res.minute, res.second) = self._parse_min_sec(value)
|
1052 |
+
|
1053 |
+
elif hms == 2:
|
1054 |
+
(res.second, res.microsecond) = self._parsems(value_repr)
|
1055 |
+
|
1056 |
+
def _could_be_tzname(self, hour, tzname, tzoffset, token):
|
1057 |
+
return (hour is not None and
|
1058 |
+
tzname is None and
|
1059 |
+
tzoffset is None and
|
1060 |
+
len(token) <= 5 and
|
1061 |
+
(all(x in string.ascii_uppercase for x in token)
|
1062 |
+
or token in self.info.UTCZONE))
|
1063 |
+
|
1064 |
+
def _ampm_valid(self, hour, ampm, fuzzy):
|
1065 |
+
"""
|
1066 |
+
For fuzzy parsing, 'a' or 'am' (both valid English words)
|
1067 |
+
may erroneously trigger the AM/PM flag. Deal with that
|
1068 |
+
here.
|
1069 |
+
"""
|
1070 |
+
val_is_ampm = True
|
1071 |
+
|
1072 |
+
# If there's already an AM/PM flag, this one isn't one.
|
1073 |
+
if fuzzy and ampm is not None:
|
1074 |
+
val_is_ampm = False
|
1075 |
+
|
1076 |
+
# If AM/PM is found and hour is not, raise a ValueError
|
1077 |
+
if hour is None:
|
1078 |
+
if fuzzy:
|
1079 |
+
val_is_ampm = False
|
1080 |
+
else:
|
1081 |
+
raise ValueError('No hour specified with AM or PM flag.')
|
1082 |
+
elif not 0 <= hour <= 12:
|
1083 |
+
# If AM/PM is found, it's a 12 hour clock, so raise
|
1084 |
+
# an error for invalid range
|
1085 |
+
if fuzzy:
|
1086 |
+
val_is_ampm = False
|
1087 |
+
else:
|
1088 |
+
raise ValueError('Invalid hour specified for 12-hour clock.')
|
1089 |
+
|
1090 |
+
return val_is_ampm
|
1091 |
+
|
1092 |
+
def _adjust_ampm(self, hour, ampm):
|
1093 |
+
if hour < 12 and ampm == 1:
|
1094 |
+
hour += 12
|
1095 |
+
elif hour == 12 and ampm == 0:
|
1096 |
+
hour = 0
|
1097 |
+
return hour
|
1098 |
+
|
1099 |
+
def _parse_min_sec(self, value):
|
1100 |
+
# TODO: Every usage of this function sets res.second to the return
|
1101 |
+
# value. Are there any cases where second will be returned as None and
|
1102 |
+
# we *don't* want to set res.second = None?
|
1103 |
+
minute = int(value)
|
1104 |
+
second = None
|
1105 |
+
|
1106 |
+
sec_remainder = value % 1
|
1107 |
+
if sec_remainder:
|
1108 |
+
second = int(60 * sec_remainder)
|
1109 |
+
return (minute, second)
|
1110 |
+
|
1111 |
+
def _parse_hms(self, idx, tokens, info, hms_idx):
|
1112 |
+
# TODO: Is this going to admit a lot of false-positives for when we
|
1113 |
+
# just happen to have digits and "h", "m" or "s" characters in non-date
|
1114 |
+
# text? I guess hex hashes won't have that problem, but there's plenty
|
1115 |
+
# of random junk out there.
|
1116 |
+
if hms_idx is None:
|
1117 |
+
hms = None
|
1118 |
+
new_idx = idx
|
1119 |
+
elif hms_idx > idx:
|
1120 |
+
hms = info.hms(tokens[hms_idx])
|
1121 |
+
new_idx = hms_idx
|
1122 |
+
else:
|
1123 |
+
# Looking backwards, increment one.
|
1124 |
+
hms = info.hms(tokens[hms_idx]) + 1
|
1125 |
+
new_idx = idx
|
1126 |
+
|
1127 |
+
return (new_idx, hms)
|
1128 |
+
|
1129 |
+
# ------------------------------------------------------------------
|
1130 |
+
# Handling for individual tokens. These are kept as methods instead
|
1131 |
+
# of functions for the sake of customizability via subclassing.
|
1132 |
+
|
1133 |
+
def _parsems(self, value):
|
1134 |
+
"""Parse a I[.F] seconds value into (seconds, microseconds)."""
|
1135 |
+
if "." not in value:
|
1136 |
+
return int(value), 0
|
1137 |
+
else:
|
1138 |
+
i, f = value.split(".")
|
1139 |
+
return int(i), int(f.ljust(6, "0")[:6])
|
1140 |
+
|
1141 |
+
def _to_decimal(self, val):
|
1142 |
+
try:
|
1143 |
+
decimal_value = Decimal(val)
|
1144 |
+
# See GH 662, edge case, infinite value should not be converted
|
1145 |
+
# via `_to_decimal`
|
1146 |
+
if not decimal_value.is_finite():
|
1147 |
+
raise ValueError("Converted decimal value is infinite or NaN")
|
1148 |
+
except Exception as e:
|
1149 |
+
msg = "Could not convert %s to decimal" % val
|
1150 |
+
six.raise_from(ValueError(msg), e)
|
1151 |
+
else:
|
1152 |
+
return decimal_value
|
1153 |
+
|
1154 |
+
# ------------------------------------------------------------------
|
1155 |
+
# Post-Parsing construction of datetime output. These are kept as
|
1156 |
+
# methods instead of functions for the sake of customizability via
|
1157 |
+
# subclassing.
|
1158 |
+
|
1159 |
+
def _build_tzinfo(self, tzinfos, tzname, tzoffset):
|
1160 |
+
if callable(tzinfos):
|
1161 |
+
tzdata = tzinfos(tzname, tzoffset)
|
1162 |
+
else:
|
1163 |
+
tzdata = tzinfos.get(tzname)
|
1164 |
+
# handle case where tzinfo is paased an options that returns None
|
1165 |
+
# eg tzinfos = {'BRST' : None}
|
1166 |
+
if isinstance(tzdata, datetime.tzinfo) or tzdata is None:
|
1167 |
+
tzinfo = tzdata
|
1168 |
+
elif isinstance(tzdata, text_type):
|
1169 |
+
tzinfo = tz.tzstr(tzdata)
|
1170 |
+
elif isinstance(tzdata, integer_types):
|
1171 |
+
tzinfo = tz.tzoffset(tzname, tzdata)
|
1172 |
+
else:
|
1173 |
+
raise TypeError("Offset must be tzinfo subclass, tz string, "
|
1174 |
+
"or int offset.")
|
1175 |
+
return tzinfo
|
1176 |
+
|
1177 |
+
def _build_tzaware(self, naive, res, tzinfos):
|
1178 |
+
if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)):
|
1179 |
+
tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset)
|
1180 |
+
aware = naive.replace(tzinfo=tzinfo)
|
1181 |
+
aware = self._assign_tzname(aware, res.tzname)
|
1182 |
+
|
1183 |
+
elif res.tzname and res.tzname in time.tzname:
|
1184 |
+
aware = naive.replace(tzinfo=tz.tzlocal())
|
1185 |
+
|
1186 |
+
# Handle ambiguous local datetime
|
1187 |
+
aware = self._assign_tzname(aware, res.tzname)
|
1188 |
+
|
1189 |
+
# This is mostly relevant for winter GMT zones parsed in the UK
|
1190 |
+
if (aware.tzname() != res.tzname and
|
1191 |
+
res.tzname in self.info.UTCZONE):
|
1192 |
+
aware = aware.replace(tzinfo=tz.UTC)
|
1193 |
+
|
1194 |
+
elif res.tzoffset == 0:
|
1195 |
+
aware = naive.replace(tzinfo=tz.UTC)
|
1196 |
+
|
1197 |
+
elif res.tzoffset:
|
1198 |
+
aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset))
|
1199 |
+
|
1200 |
+
elif not res.tzname and not res.tzoffset:
|
1201 |
+
# i.e. no timezone information was found.
|
1202 |
+
aware = naive
|
1203 |
+
|
1204 |
+
elif res.tzname:
|
1205 |
+
# tz-like string was parsed but we don't know what to do
|
1206 |
+
# with it
|
1207 |
+
warnings.warn("tzname {tzname} identified but not understood. "
|
1208 |
+
"Pass `tzinfos` argument in order to correctly "
|
1209 |
+
"return a timezone-aware datetime. In a future "
|
1210 |
+
"version, this will raise an "
|
1211 |
+
"exception.".format(tzname=res.tzname),
|
1212 |
+
category=UnknownTimezoneWarning)
|
1213 |
+
aware = naive
|
1214 |
+
|
1215 |
+
return aware
|
1216 |
+
|
1217 |
+
def _build_naive(self, res, default):
|
1218 |
+
repl = {}
|
1219 |
+
for attr in ("year", "month", "day", "hour",
|
1220 |
+
"minute", "second", "microsecond"):
|
1221 |
+
value = getattr(res, attr)
|
1222 |
+
if value is not None:
|
1223 |
+
repl[attr] = value
|
1224 |
+
|
1225 |
+
if 'day' not in repl:
|
1226 |
+
# If the default day exceeds the last day of the month, fall back
|
1227 |
+
# to the end of the month.
|
1228 |
+
cyear = default.year if res.year is None else res.year
|
1229 |
+
cmonth = default.month if res.month is None else res.month
|
1230 |
+
cday = default.day if res.day is None else res.day
|
1231 |
+
|
1232 |
+
if cday > monthrange(cyear, cmonth)[1]:
|
1233 |
+
repl['day'] = monthrange(cyear, cmonth)[1]
|
1234 |
+
|
1235 |
+
naive = default.replace(**repl)
|
1236 |
+
|
1237 |
+
if res.weekday is not None and not res.day:
|
1238 |
+
naive = naive + relativedelta.relativedelta(weekday=res.weekday)
|
1239 |
+
|
1240 |
+
return naive
|
1241 |
+
|
1242 |
+
def _assign_tzname(self, dt, tzname):
|
1243 |
+
if dt.tzname() != tzname:
|
1244 |
+
new_dt = tz.enfold(dt, fold=1)
|
1245 |
+
if new_dt.tzname() == tzname:
|
1246 |
+
return new_dt
|
1247 |
+
|
1248 |
+
return dt
|
1249 |
+
|
1250 |
+
def _recombine_skipped(self, tokens, skipped_idxs):
|
1251 |
+
"""
|
1252 |
+
>>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"]
|
1253 |
+
>>> skipped_idxs = [0, 1, 2, 5]
|
1254 |
+
>>> _recombine_skipped(tokens, skipped_idxs)
|
1255 |
+
["foo bar", "baz"]
|
1256 |
+
"""
|
1257 |
+
skipped_tokens = []
|
1258 |
+
for i, idx in enumerate(sorted(skipped_idxs)):
|
1259 |
+
if i > 0 and idx - 1 == skipped_idxs[i - 1]:
|
1260 |
+
skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx]
|
1261 |
+
else:
|
1262 |
+
skipped_tokens.append(tokens[idx])
|
1263 |
+
|
1264 |
+
return skipped_tokens
|
1265 |
+
|
1266 |
+
|
1267 |
+
DEFAULTPARSER = parser()
|
1268 |
+
|
1269 |
+
|
1270 |
+
def parse(timestr, parserinfo=None, **kwargs):
|
1271 |
+
"""
|
1272 |
+
|
1273 |
+
Parse a string in one of the supported formats, using the
|
1274 |
+
``parserinfo`` parameters.
|
1275 |
+
|
1276 |
+
:param timestr:
|
1277 |
+
A string containing a date/time stamp.
|
1278 |
+
|
1279 |
+
:param parserinfo:
|
1280 |
+
A :class:`parserinfo` object containing parameters for the parser.
|
1281 |
+
If ``None``, the default arguments to the :class:`parserinfo`
|
1282 |
+
constructor are used.
|
1283 |
+
|
1284 |
+
The ``**kwargs`` parameter takes the following keyword arguments:
|
1285 |
+
|
1286 |
+
:param default:
|
1287 |
+
The default datetime object, if this is a datetime object and not
|
1288 |
+
``None``, elements specified in ``timestr`` replace elements in the
|
1289 |
+
default object.
|
1290 |
+
|
1291 |
+
:param ignoretz:
|
1292 |
+
If set ``True``, time zones in parsed strings are ignored and a naive
|
1293 |
+
:class:`datetime` object is returned.
|
1294 |
+
|
1295 |
+
:param tzinfos:
|
1296 |
+
Additional time zone names / aliases which may be present in the
|
1297 |
+
string. This argument maps time zone names (and optionally offsets
|
1298 |
+
from those time zones) to time zones. This parameter can be a
|
1299 |
+
dictionary with timezone aliases mapping time zone names to time
|
1300 |
+
zones or a function taking two parameters (``tzname`` and
|
1301 |
+
``tzoffset``) and returning a time zone.
|
1302 |
+
|
1303 |
+
The timezones to which the names are mapped can be an integer
|
1304 |
+
offset from UTC in seconds or a :class:`tzinfo` object.
|
1305 |
+
|
1306 |
+
.. doctest::
|
1307 |
+
:options: +NORMALIZE_WHITESPACE
|
1308 |
+
|
1309 |
+
>>> from dateutil.parser import parse
|
1310 |
+
>>> from dateutil.tz import gettz
|
1311 |
+
>>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")}
|
1312 |
+
>>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos)
|
1313 |
+
datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200))
|
1314 |
+
>>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos)
|
1315 |
+
datetime.datetime(2012, 1, 19, 17, 21,
|
1316 |
+
tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago'))
|
1317 |
+
|
1318 |
+
This parameter is ignored if ``ignoretz`` is set.
|
1319 |
+
|
1320 |
+
:param dayfirst:
|
1321 |
+
Whether to interpret the first value in an ambiguous 3-integer date
|
1322 |
+
(e.g. 01/05/09) as the day (``True``) or month (``False``). If
|
1323 |
+
``yearfirst`` is set to ``True``, this distinguishes between YDM and
|
1324 |
+
YMD. If set to ``None``, this value is retrieved from the current
|
1325 |
+
:class:`parserinfo` object (which itself defaults to ``False``).
|
1326 |
+
|
1327 |
+
:param yearfirst:
|
1328 |
+
Whether to interpret the first value in an ambiguous 3-integer date
|
1329 |
+
(e.g. 01/05/09) as the year. If ``True``, the first number is taken to
|
1330 |
+
be the year, otherwise the last number is taken to be the year. If
|
1331 |
+
this is set to ``None``, the value is retrieved from the current
|
1332 |
+
:class:`parserinfo` object (which itself defaults to ``False``).
|
1333 |
+
|
1334 |
+
:param fuzzy:
|
1335 |
+
Whether to allow fuzzy parsing, allowing for string like "Today is
|
1336 |
+
January 1, 2047 at 8:21:00AM".
|
1337 |
+
|
1338 |
+
:param fuzzy_with_tokens:
|
1339 |
+
If ``True``, ``fuzzy`` is automatically set to True, and the parser
|
1340 |
+
will return a tuple where the first element is the parsed
|
1341 |
+
:class:`datetime.datetime` datetimestamp and the second element is
|
1342 |
+
a tuple containing the portions of the string which were ignored:
|
1343 |
+
|
1344 |
+
.. doctest::
|
1345 |
+
|
1346 |
+
>>> from dateutil.parser import parse
|
1347 |
+
>>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True)
|
1348 |
+
(datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))
|
1349 |
+
|
1350 |
+
:return:
|
1351 |
+
Returns a :class:`datetime.datetime` object or, if the
|
1352 |
+
``fuzzy_with_tokens`` option is ``True``, returns a tuple, the
|
1353 |
+
first element being a :class:`datetime.datetime` object, the second
|
1354 |
+
a tuple containing the fuzzy tokens.
|
1355 |
+
|
1356 |
+
:raises ParserError:
|
1357 |
+
Raised for invalid or unknown string formats, if the provided
|
1358 |
+
:class:`tzinfo` is not in a valid format, or if an invalid date would
|
1359 |
+
be created.
|
1360 |
+
|
1361 |
+
:raises OverflowError:
|
1362 |
+
Raised if the parsed date exceeds the largest valid C integer on
|
1363 |
+
your system.
|
1364 |
+
"""
|
1365 |
+
if parserinfo:
|
1366 |
+
return parser(parserinfo).parse(timestr, **kwargs)
|
1367 |
+
else:
|
1368 |
+
return DEFAULTPARSER.parse(timestr, **kwargs)
|
1369 |
+
|
1370 |
+
|
1371 |
+
class _tzparser(object):
|
1372 |
+
|
1373 |
+
class _result(_resultbase):
|
1374 |
+
|
1375 |
+
__slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset",
|
1376 |
+
"start", "end"]
|
1377 |
+
|
1378 |
+
class _attr(_resultbase):
|
1379 |
+
__slots__ = ["month", "week", "weekday",
|
1380 |
+
"yday", "jyday", "day", "time"]
|
1381 |
+
|
1382 |
+
def __repr__(self):
|
1383 |
+
return self._repr("")
|
1384 |
+
|
1385 |
+
def __init__(self):
|
1386 |
+
_resultbase.__init__(self)
|
1387 |
+
self.start = self._attr()
|
1388 |
+
self.end = self._attr()
|
1389 |
+
|
1390 |
+
def parse(self, tzstr):
|
1391 |
+
res = self._result()
|
1392 |
+
l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x]
|
1393 |
+
used_idxs = list()
|
1394 |
+
try:
|
1395 |
+
|
1396 |
+
len_l = len(l)
|
1397 |
+
|
1398 |
+
i = 0
|
1399 |
+
while i < len_l:
|
1400 |
+
# BRST+3[BRDT[+2]]
|
1401 |
+
j = i
|
1402 |
+
while j < len_l and not [x for x in l[j]
|
1403 |
+
if x in "0123456789:,-+"]:
|
1404 |
+
j += 1
|
1405 |
+
if j != i:
|
1406 |
+
if not res.stdabbr:
|
1407 |
+
offattr = "stdoffset"
|
1408 |
+
res.stdabbr = "".join(l[i:j])
|
1409 |
+
else:
|
1410 |
+
offattr = "dstoffset"
|
1411 |
+
res.dstabbr = "".join(l[i:j])
|
1412 |
+
|
1413 |
+
for ii in range(j):
|
1414 |
+
used_idxs.append(ii)
|
1415 |
+
i = j
|
1416 |
+
if (i < len_l and (l[i] in ('+', '-') or l[i][0] in
|
1417 |
+
"0123456789")):
|
1418 |
+
if l[i] in ('+', '-'):
|
1419 |
+
# Yes, that's right. See the TZ variable
|
1420 |
+
# documentation.
|
1421 |
+
signal = (1, -1)[l[i] == '+']
|
1422 |
+
used_idxs.append(i)
|
1423 |
+
i += 1
|
1424 |
+
else:
|
1425 |
+
signal = -1
|
1426 |
+
len_li = len(l[i])
|
1427 |
+
if len_li == 4:
|
1428 |
+
# -0300
|
1429 |
+
setattr(res, offattr, (int(l[i][:2]) * 3600 +
|
1430 |
+
int(l[i][2:]) * 60) * signal)
|
1431 |
+
elif i + 1 < len_l and l[i + 1] == ':':
|
1432 |
+
# -03:00
|
1433 |
+
setattr(res, offattr,
|
1434 |
+
(int(l[i]) * 3600 +
|
1435 |
+
int(l[i + 2]) * 60) * signal)
|
1436 |
+
used_idxs.append(i)
|
1437 |
+
i += 2
|
1438 |
+
elif len_li <= 2:
|
1439 |
+
# -[0]3
|
1440 |
+
setattr(res, offattr,
|
1441 |
+
int(l[i][:2]) * 3600 * signal)
|
1442 |
+
else:
|
1443 |
+
return None
|
1444 |
+
used_idxs.append(i)
|
1445 |
+
i += 1
|
1446 |
+
if res.dstabbr:
|
1447 |
+
break
|
1448 |
+
else:
|
1449 |
+
break
|
1450 |
+
|
1451 |
+
|
1452 |
+
if i < len_l:
|
1453 |
+
for j in range(i, len_l):
|
1454 |
+
if l[j] == ';':
|
1455 |
+
l[j] = ','
|
1456 |
+
|
1457 |
+
assert l[i] == ','
|
1458 |
+
|
1459 |
+
i += 1
|
1460 |
+
|
1461 |
+
if i >= len_l:
|
1462 |
+
pass
|
1463 |
+
elif (8 <= l.count(',') <= 9 and
|
1464 |
+
not [y for x in l[i:] if x != ','
|
1465 |
+
for y in x if y not in "0123456789+-"]):
|
1466 |
+
# GMT0BST,3,0,30,3600,10,0,26,7200[,3600]
|
1467 |
+
for x in (res.start, res.end):
|
1468 |
+
x.month = int(l[i])
|
1469 |
+
used_idxs.append(i)
|
1470 |
+
i += 2
|
1471 |
+
if l[i] == '-':
|
1472 |
+
value = int(l[i + 1]) * -1
|
1473 |
+
used_idxs.append(i)
|
1474 |
+
i += 1
|
1475 |
+
else:
|
1476 |
+
value = int(l[i])
|
1477 |
+
used_idxs.append(i)
|
1478 |
+
i += 2
|
1479 |
+
if value:
|
1480 |
+
x.week = value
|
1481 |
+
x.weekday = (int(l[i]) - 1) % 7
|
1482 |
+
else:
|
1483 |
+
x.day = int(l[i])
|
1484 |
+
used_idxs.append(i)
|
1485 |
+
i += 2
|
1486 |
+
x.time = int(l[i])
|
1487 |
+
used_idxs.append(i)
|
1488 |
+
i += 2
|
1489 |
+
if i < len_l:
|
1490 |
+
if l[i] in ('-', '+'):
|
1491 |
+
signal = (-1, 1)[l[i] == "+"]
|
1492 |
+
used_idxs.append(i)
|
1493 |
+
i += 1
|
1494 |
+
else:
|
1495 |
+
signal = 1
|
1496 |
+
used_idxs.append(i)
|
1497 |
+
res.dstoffset = (res.stdoffset + int(l[i]) * signal)
|
1498 |
+
|
1499 |
+
# This was a made-up format that is not in normal use
|
1500 |
+
warn(('Parsed time zone "%s"' % tzstr) +
|
1501 |
+
'is in a non-standard dateutil-specific format, which ' +
|
1502 |
+
'is now deprecated; support for parsing this format ' +
|
1503 |
+
'will be removed in future versions. It is recommended ' +
|
1504 |
+
'that you switch to a standard format like the GNU ' +
|
1505 |
+
'TZ variable format.', tz.DeprecatedTzFormatWarning)
|
1506 |
+
elif (l.count(',') == 2 and l[i:].count('/') <= 2 and
|
1507 |
+
not [y for x in l[i:] if x not in (',', '/', 'J', 'M',
|
1508 |
+
'.', '-', ':')
|
1509 |
+
for y in x if y not in "0123456789"]):
|
1510 |
+
for x in (res.start, res.end):
|
1511 |
+
if l[i] == 'J':
|
1512 |
+
# non-leap year day (1 based)
|
1513 |
+
used_idxs.append(i)
|
1514 |
+
i += 1
|
1515 |
+
x.jyday = int(l[i])
|
1516 |
+
elif l[i] == 'M':
|
1517 |
+
# month[-.]week[-.]weekday
|
1518 |
+
used_idxs.append(i)
|
1519 |
+
i += 1
|
1520 |
+
x.month = int(l[i])
|
1521 |
+
used_idxs.append(i)
|
1522 |
+
i += 1
|
1523 |
+
assert l[i] in ('-', '.')
|
1524 |
+
used_idxs.append(i)
|
1525 |
+
i += 1
|
1526 |
+
x.week = int(l[i])
|
1527 |
+
if x.week == 5:
|
1528 |
+
x.week = -1
|
1529 |
+
used_idxs.append(i)
|
1530 |
+
i += 1
|
1531 |
+
assert l[i] in ('-', '.')
|
1532 |
+
used_idxs.append(i)
|
1533 |
+
i += 1
|
1534 |
+
x.weekday = (int(l[i]) - 1) % 7
|
1535 |
+
else:
|
1536 |
+
# year day (zero based)
|
1537 |
+
x.yday = int(l[i]) + 1
|
1538 |
+
|
1539 |
+
used_idxs.append(i)
|
1540 |
+
i += 1
|
1541 |
+
|
1542 |
+
if i < len_l and l[i] == '/':
|
1543 |
+
used_idxs.append(i)
|
1544 |
+
i += 1
|
1545 |
+
# start time
|
1546 |
+
len_li = len(l[i])
|
1547 |
+
if len_li == 4:
|
1548 |
+
# -0300
|
1549 |
+
x.time = (int(l[i][:2]) * 3600 +
|
1550 |
+
int(l[i][2:]) * 60)
|
1551 |
+
elif i + 1 < len_l and l[i + 1] == ':':
|
1552 |
+
# -03:00
|
1553 |
+
x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60
|
1554 |
+
used_idxs.append(i)
|
1555 |
+
i += 2
|
1556 |
+
if i + 1 < len_l and l[i + 1] == ':':
|
1557 |
+
used_idxs.append(i)
|
1558 |
+
i += 2
|
1559 |
+
x.time += int(l[i])
|
1560 |
+
elif len_li <= 2:
|
1561 |
+
# -[0]3
|
1562 |
+
x.time = (int(l[i][:2]) * 3600)
|
1563 |
+
else:
|
1564 |
+
return None
|
1565 |
+
used_idxs.append(i)
|
1566 |
+
i += 1
|
1567 |
+
|
1568 |
+
assert i == len_l or l[i] == ','
|
1569 |
+
|
1570 |
+
i += 1
|
1571 |
+
|
1572 |
+
assert i >= len_l
|
1573 |
+
|
1574 |
+
except (IndexError, ValueError, AssertionError):
|
1575 |
+
return None
|
1576 |
+
|
1577 |
+
unused_idxs = set(range(len_l)).difference(used_idxs)
|
1578 |
+
res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"})
|
1579 |
+
return res
|
1580 |
+
|
1581 |
+
|
1582 |
+
DEFAULTTZPARSER = _tzparser()
|
1583 |
+
|
1584 |
+
|
1585 |
+
def _parsetz(tzstr):
|
1586 |
+
return DEFAULTTZPARSER.parse(tzstr)
|
1587 |
+
|
1588 |
+
|
1589 |
+
class ParserError(ValueError):
|
1590 |
+
"""Exception subclass used for any failure to parse a datetime string.
|
1591 |
+
|
1592 |
+
This is a subclass of :py:exc:`ValueError`, and should be raised any time
|
1593 |
+
earlier versions of ``dateutil`` would have raised ``ValueError``.
|
1594 |
+
|
1595 |
+
.. versionadded:: 2.8.1
|
1596 |
+
"""
|
1597 |
+
def __str__(self):
|
1598 |
+
try:
|
1599 |
+
return self.args[0] % self.args[1:]
|
1600 |
+
except (TypeError, IndexError):
|
1601 |
+
return super(ParserError, self).__str__()
|
1602 |
+
|
1603 |
+
def __repr__(self):
|
1604 |
+
args = ", ".join("'%s'" % arg for arg in self.args)
|
1605 |
+
return "%s(%s)" % (self.__class__.__name__, args)
|
1606 |
+
|
1607 |
+
|
1608 |
+
class UnknownTimezoneWarning(RuntimeWarning):
|
1609 |
+
"""Raised when the parser finds a timezone it cannot parse into a tzinfo.
|
1610 |
+
|
1611 |
+
.. versionadded:: 2.7.0
|
1612 |
+
"""
|
1613 |
+
# vim:ts=4:sw=4:et
|
venv/lib/python3.10/site-packages/dateutil/parser/isoparser.py
ADDED
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
This module offers a parser for ISO-8601 strings
|
4 |
+
|
5 |
+
It is intended to support all valid date, time and datetime formats per the
|
6 |
+
ISO-8601 specification.
|
7 |
+
|
8 |
+
..versionadded:: 2.7.0
|
9 |
+
"""
|
10 |
+
from datetime import datetime, timedelta, time, date
|
11 |
+
import calendar
|
12 |
+
from dateutil import tz
|
13 |
+
|
14 |
+
from functools import wraps
|
15 |
+
|
16 |
+
import re
|
17 |
+
import six
|
18 |
+
|
19 |
+
__all__ = ["isoparse", "isoparser"]
|
20 |
+
|
21 |
+
|
22 |
+
def _takes_ascii(f):
|
23 |
+
@wraps(f)
|
24 |
+
def func(self, str_in, *args, **kwargs):
|
25 |
+
# If it's a stream, read the whole thing
|
26 |
+
str_in = getattr(str_in, 'read', lambda: str_in)()
|
27 |
+
|
28 |
+
# If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII
|
29 |
+
if isinstance(str_in, six.text_type):
|
30 |
+
# ASCII is the same in UTF-8
|
31 |
+
try:
|
32 |
+
str_in = str_in.encode('ascii')
|
33 |
+
except UnicodeEncodeError as e:
|
34 |
+
msg = 'ISO-8601 strings should contain only ASCII characters'
|
35 |
+
six.raise_from(ValueError(msg), e)
|
36 |
+
|
37 |
+
return f(self, str_in, *args, **kwargs)
|
38 |
+
|
39 |
+
return func
|
40 |
+
|
41 |
+
|
42 |
+
class isoparser(object):
|
43 |
+
def __init__(self, sep=None):
|
44 |
+
"""
|
45 |
+
:param sep:
|
46 |
+
A single character that separates date and time portions. If
|
47 |
+
``None``, the parser will accept any single character.
|
48 |
+
For strict ISO-8601 adherence, pass ``'T'``.
|
49 |
+
"""
|
50 |
+
if sep is not None:
|
51 |
+
if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'):
|
52 |
+
raise ValueError('Separator must be a single, non-numeric ' +
|
53 |
+
'ASCII character')
|
54 |
+
|
55 |
+
sep = sep.encode('ascii')
|
56 |
+
|
57 |
+
self._sep = sep
|
58 |
+
|
59 |
+
@_takes_ascii
|
60 |
+
def isoparse(self, dt_str):
|
61 |
+
"""
|
62 |
+
Parse an ISO-8601 datetime string into a :class:`datetime.datetime`.
|
63 |
+
|
64 |
+
An ISO-8601 datetime string consists of a date portion, followed
|
65 |
+
optionally by a time portion - the date and time portions are separated
|
66 |
+
by a single character separator, which is ``T`` in the official
|
67 |
+
standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be
|
68 |
+
combined with a time portion.
|
69 |
+
|
70 |
+
Supported date formats are:
|
71 |
+
|
72 |
+
Common:
|
73 |
+
|
74 |
+
- ``YYYY``
|
75 |
+
- ``YYYY-MM``
|
76 |
+
- ``YYYY-MM-DD`` or ``YYYYMMDD``
|
77 |
+
|
78 |
+
Uncommon:
|
79 |
+
|
80 |
+
- ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0)
|
81 |
+
- ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day
|
82 |
+
|
83 |
+
The ISO week and day numbering follows the same logic as
|
84 |
+
:func:`datetime.date.isocalendar`.
|
85 |
+
|
86 |
+
Supported time formats are:
|
87 |
+
|
88 |
+
- ``hh``
|
89 |
+
- ``hh:mm`` or ``hhmm``
|
90 |
+
- ``hh:mm:ss`` or ``hhmmss``
|
91 |
+
- ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits)
|
92 |
+
|
93 |
+
Midnight is a special case for `hh`, as the standard supports both
|
94 |
+
00:00 and 24:00 as a representation. The decimal separator can be
|
95 |
+
either a dot or a comma.
|
96 |
+
|
97 |
+
|
98 |
+
.. caution::
|
99 |
+
|
100 |
+
Support for fractional components other than seconds is part of the
|
101 |
+
ISO-8601 standard, but is not currently implemented in this parser.
|
102 |
+
|
103 |
+
Supported time zone offset formats are:
|
104 |
+
|
105 |
+
- `Z` (UTC)
|
106 |
+
- `±HH:MM`
|
107 |
+
- `±HHMM`
|
108 |
+
- `±HH`
|
109 |
+
|
110 |
+
Offsets will be represented as :class:`dateutil.tz.tzoffset` objects,
|
111 |
+
with the exception of UTC, which will be represented as
|
112 |
+
:class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such
|
113 |
+
as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`.
|
114 |
+
|
115 |
+
:param dt_str:
|
116 |
+
A string or stream containing only an ISO-8601 datetime string
|
117 |
+
|
118 |
+
:return:
|
119 |
+
Returns a :class:`datetime.datetime` representing the string.
|
120 |
+
Unspecified components default to their lowest value.
|
121 |
+
|
122 |
+
.. warning::
|
123 |
+
|
124 |
+
As of version 2.7.0, the strictness of the parser should not be
|
125 |
+
considered a stable part of the contract. Any valid ISO-8601 string
|
126 |
+
that parses correctly with the default settings will continue to
|
127 |
+
parse correctly in future versions, but invalid strings that
|
128 |
+
currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not
|
129 |
+
guaranteed to continue failing in future versions if they encode
|
130 |
+
a valid date.
|
131 |
+
|
132 |
+
.. versionadded:: 2.7.0
|
133 |
+
"""
|
134 |
+
components, pos = self._parse_isodate(dt_str)
|
135 |
+
|
136 |
+
if len(dt_str) > pos:
|
137 |
+
if self._sep is None or dt_str[pos:pos + 1] == self._sep:
|
138 |
+
components += self._parse_isotime(dt_str[pos + 1:])
|
139 |
+
else:
|
140 |
+
raise ValueError('String contains unknown ISO components')
|
141 |
+
|
142 |
+
if len(components) > 3 and components[3] == 24:
|
143 |
+
components[3] = 0
|
144 |
+
return datetime(*components) + timedelta(days=1)
|
145 |
+
|
146 |
+
return datetime(*components)
|
147 |
+
|
148 |
+
@_takes_ascii
|
149 |
+
def parse_isodate(self, datestr):
|
150 |
+
"""
|
151 |
+
Parse the date portion of an ISO string.
|
152 |
+
|
153 |
+
:param datestr:
|
154 |
+
The string portion of an ISO string, without a separator
|
155 |
+
|
156 |
+
:return:
|
157 |
+
Returns a :class:`datetime.date` object
|
158 |
+
"""
|
159 |
+
components, pos = self._parse_isodate(datestr)
|
160 |
+
if pos < len(datestr):
|
161 |
+
raise ValueError('String contains unknown ISO ' +
|
162 |
+
'components: {!r}'.format(datestr.decode('ascii')))
|
163 |
+
return date(*components)
|
164 |
+
|
165 |
+
@_takes_ascii
|
166 |
+
def parse_isotime(self, timestr):
|
167 |
+
"""
|
168 |
+
Parse the time portion of an ISO string.
|
169 |
+
|
170 |
+
:param timestr:
|
171 |
+
The time portion of an ISO string, without a separator
|
172 |
+
|
173 |
+
:return:
|
174 |
+
Returns a :class:`datetime.time` object
|
175 |
+
"""
|
176 |
+
components = self._parse_isotime(timestr)
|
177 |
+
if components[0] == 24:
|
178 |
+
components[0] = 0
|
179 |
+
return time(*components)
|
180 |
+
|
181 |
+
@_takes_ascii
|
182 |
+
def parse_tzstr(self, tzstr, zero_as_utc=True):
|
183 |
+
"""
|
184 |
+
Parse a valid ISO time zone string.
|
185 |
+
|
186 |
+
See :func:`isoparser.isoparse` for details on supported formats.
|
187 |
+
|
188 |
+
:param tzstr:
|
189 |
+
A string representing an ISO time zone offset
|
190 |
+
|
191 |
+
:param zero_as_utc:
|
192 |
+
Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones
|
193 |
+
|
194 |
+
:return:
|
195 |
+
Returns :class:`dateutil.tz.tzoffset` for offsets and
|
196 |
+
:class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
|
197 |
+
specified) offsets equivalent to UTC.
|
198 |
+
"""
|
199 |
+
return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)
|
200 |
+
|
201 |
+
# Constants
|
202 |
+
_DATE_SEP = b'-'
|
203 |
+
_TIME_SEP = b':'
|
204 |
+
_FRACTION_REGEX = re.compile(b'[\\.,]([0-9]+)')
|
205 |
+
|
206 |
+
def _parse_isodate(self, dt_str):
|
207 |
+
try:
|
208 |
+
return self._parse_isodate_common(dt_str)
|
209 |
+
except ValueError:
|
210 |
+
return self._parse_isodate_uncommon(dt_str)
|
211 |
+
|
212 |
+
def _parse_isodate_common(self, dt_str):
|
213 |
+
len_str = len(dt_str)
|
214 |
+
components = [1, 1, 1]
|
215 |
+
|
216 |
+
if len_str < 4:
|
217 |
+
raise ValueError('ISO string too short')
|
218 |
+
|
219 |
+
# Year
|
220 |
+
components[0] = int(dt_str[0:4])
|
221 |
+
pos = 4
|
222 |
+
if pos >= len_str:
|
223 |
+
return components, pos
|
224 |
+
|
225 |
+
has_sep = dt_str[pos:pos + 1] == self._DATE_SEP
|
226 |
+
if has_sep:
|
227 |
+
pos += 1
|
228 |
+
|
229 |
+
# Month
|
230 |
+
if len_str - pos < 2:
|
231 |
+
raise ValueError('Invalid common month')
|
232 |
+
|
233 |
+
components[1] = int(dt_str[pos:pos + 2])
|
234 |
+
pos += 2
|
235 |
+
|
236 |
+
if pos >= len_str:
|
237 |
+
if has_sep:
|
238 |
+
return components, pos
|
239 |
+
else:
|
240 |
+
raise ValueError('Invalid ISO format')
|
241 |
+
|
242 |
+
if has_sep:
|
243 |
+
if dt_str[pos:pos + 1] != self._DATE_SEP:
|
244 |
+
raise ValueError('Invalid separator in ISO string')
|
245 |
+
pos += 1
|
246 |
+
|
247 |
+
# Day
|
248 |
+
if len_str - pos < 2:
|
249 |
+
raise ValueError('Invalid common day')
|
250 |
+
components[2] = int(dt_str[pos:pos + 2])
|
251 |
+
return components, pos + 2
|
252 |
+
|
253 |
+
def _parse_isodate_uncommon(self, dt_str):
|
254 |
+
if len(dt_str) < 4:
|
255 |
+
raise ValueError('ISO string too short')
|
256 |
+
|
257 |
+
# All ISO formats start with the year
|
258 |
+
year = int(dt_str[0:4])
|
259 |
+
|
260 |
+
has_sep = dt_str[4:5] == self._DATE_SEP
|
261 |
+
|
262 |
+
pos = 4 + has_sep # Skip '-' if it's there
|
263 |
+
if dt_str[pos:pos + 1] == b'W':
|
264 |
+
# YYYY-?Www-?D?
|
265 |
+
pos += 1
|
266 |
+
weekno = int(dt_str[pos:pos + 2])
|
267 |
+
pos += 2
|
268 |
+
|
269 |
+
dayno = 1
|
270 |
+
if len(dt_str) > pos:
|
271 |
+
if (dt_str[pos:pos + 1] == self._DATE_SEP) != has_sep:
|
272 |
+
raise ValueError('Inconsistent use of dash separator')
|
273 |
+
|
274 |
+
pos += has_sep
|
275 |
+
|
276 |
+
dayno = int(dt_str[pos:pos + 1])
|
277 |
+
pos += 1
|
278 |
+
|
279 |
+
base_date = self._calculate_weekdate(year, weekno, dayno)
|
280 |
+
else:
|
281 |
+
# YYYYDDD or YYYY-DDD
|
282 |
+
if len(dt_str) - pos < 3:
|
283 |
+
raise ValueError('Invalid ordinal day')
|
284 |
+
|
285 |
+
ordinal_day = int(dt_str[pos:pos + 3])
|
286 |
+
pos += 3
|
287 |
+
|
288 |
+
if ordinal_day < 1 or ordinal_day > (365 + calendar.isleap(year)):
|
289 |
+
raise ValueError('Invalid ordinal day' +
|
290 |
+
' {} for year {}'.format(ordinal_day, year))
|
291 |
+
|
292 |
+
base_date = date(year, 1, 1) + timedelta(days=ordinal_day - 1)
|
293 |
+
|
294 |
+
components = [base_date.year, base_date.month, base_date.day]
|
295 |
+
return components, pos
|
296 |
+
|
297 |
+
def _calculate_weekdate(self, year, week, day):
|
298 |
+
"""
|
299 |
+
Calculate the day of corresponding to the ISO year-week-day calendar.
|
300 |
+
|
301 |
+
This function is effectively the inverse of
|
302 |
+
:func:`datetime.date.isocalendar`.
|
303 |
+
|
304 |
+
:param year:
|
305 |
+
The year in the ISO calendar
|
306 |
+
|
307 |
+
:param week:
|
308 |
+
The week in the ISO calendar - range is [1, 53]
|
309 |
+
|
310 |
+
:param day:
|
311 |
+
The day in the ISO calendar - range is [1 (MON), 7 (SUN)]
|
312 |
+
|
313 |
+
:return:
|
314 |
+
Returns a :class:`datetime.date`
|
315 |
+
"""
|
316 |
+
if not 0 < week < 54:
|
317 |
+
raise ValueError('Invalid week: {}'.format(week))
|
318 |
+
|
319 |
+
if not 0 < day < 8: # Range is 1-7
|
320 |
+
raise ValueError('Invalid weekday: {}'.format(day))
|
321 |
+
|
322 |
+
# Get week 1 for the specific year:
|
323 |
+
jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it
|
324 |
+
week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1)
|
325 |
+
|
326 |
+
# Now add the specific number of weeks and days to get what we want
|
327 |
+
week_offset = (week - 1) * 7 + (day - 1)
|
328 |
+
return week_1 + timedelta(days=week_offset)
|
329 |
+
|
330 |
+
def _parse_isotime(self, timestr):
|
331 |
+
len_str = len(timestr)
|
332 |
+
components = [0, 0, 0, 0, None]
|
333 |
+
pos = 0
|
334 |
+
comp = -1
|
335 |
+
|
336 |
+
if len_str < 2:
|
337 |
+
raise ValueError('ISO time too short')
|
338 |
+
|
339 |
+
has_sep = False
|
340 |
+
|
341 |
+
while pos < len_str and comp < 5:
|
342 |
+
comp += 1
|
343 |
+
|
344 |
+
if timestr[pos:pos + 1] in b'-+Zz':
|
345 |
+
# Detect time zone boundary
|
346 |
+
components[-1] = self._parse_tzstr(timestr[pos:])
|
347 |
+
pos = len_str
|
348 |
+
break
|
349 |
+
|
350 |
+
if comp == 1 and timestr[pos:pos+1] == self._TIME_SEP:
|
351 |
+
has_sep = True
|
352 |
+
pos += 1
|
353 |
+
elif comp == 2 and has_sep:
|
354 |
+
if timestr[pos:pos+1] != self._TIME_SEP:
|
355 |
+
raise ValueError('Inconsistent use of colon separator')
|
356 |
+
pos += 1
|
357 |
+
|
358 |
+
if comp < 3:
|
359 |
+
# Hour, minute, second
|
360 |
+
components[comp] = int(timestr[pos:pos + 2])
|
361 |
+
pos += 2
|
362 |
+
|
363 |
+
if comp == 3:
|
364 |
+
# Fraction of a second
|
365 |
+
frac = self._FRACTION_REGEX.match(timestr[pos:])
|
366 |
+
if not frac:
|
367 |
+
continue
|
368 |
+
|
369 |
+
us_str = frac.group(1)[:6] # Truncate to microseconds
|
370 |
+
components[comp] = int(us_str) * 10**(6 - len(us_str))
|
371 |
+
pos += len(frac.group())
|
372 |
+
|
373 |
+
if pos < len_str:
|
374 |
+
raise ValueError('Unused components in ISO string')
|
375 |
+
|
376 |
+
if components[0] == 24:
|
377 |
+
# Standard supports 00:00 and 24:00 as representations of midnight
|
378 |
+
if any(component != 0 for component in components[1:4]):
|
379 |
+
raise ValueError('Hour may only be 24 at 24:00:00.000')
|
380 |
+
|
381 |
+
return components
|
382 |
+
|
383 |
+
def _parse_tzstr(self, tzstr, zero_as_utc=True):
|
384 |
+
if tzstr == b'Z' or tzstr == b'z':
|
385 |
+
return tz.UTC
|
386 |
+
|
387 |
+
if len(tzstr) not in {3, 5, 6}:
|
388 |
+
raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters')
|
389 |
+
|
390 |
+
if tzstr[0:1] == b'-':
|
391 |
+
mult = -1
|
392 |
+
elif tzstr[0:1] == b'+':
|
393 |
+
mult = 1
|
394 |
+
else:
|
395 |
+
raise ValueError('Time zone offset requires sign')
|
396 |
+
|
397 |
+
hours = int(tzstr[1:3])
|
398 |
+
if len(tzstr) == 3:
|
399 |
+
minutes = 0
|
400 |
+
else:
|
401 |
+
minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):])
|
402 |
+
|
403 |
+
if zero_as_utc and hours == 0 and minutes == 0:
|
404 |
+
return tz.UTC
|
405 |
+
else:
|
406 |
+
if minutes > 59:
|
407 |
+
raise ValueError('Invalid minutes in time zone offset')
|
408 |
+
|
409 |
+
if hours > 23:
|
410 |
+
raise ValueError('Invalid hours in time zone offset')
|
411 |
+
|
412 |
+
return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60)
|
413 |
+
|
414 |
+
|
415 |
+
DEFAULT_ISOPARSER = isoparser()
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
The rrule module offers a small, complete, and very fast, implementation of
|
4 |
+
the recurrence rules documented in the
|
5 |
+
`iCalendar RFC <https://tools.ietf.org/html/rfc5545>`_,
|
6 |
+
including support for caching of results.
|
7 |
+
"""
|
8 |
+
import calendar
|
9 |
+
import datetime
|
10 |
+
import heapq
|
11 |
+
import itertools
|
12 |
+
import re
|
13 |
+
import sys
|
14 |
+
from functools import wraps
|
15 |
+
# For warning about deprecation of until and count
|
16 |
+
from warnings import warn
|
17 |
+
|
18 |
+
from six import advance_iterator, integer_types
|
19 |
+
|
20 |
+
from six.moves import _thread, range
|
21 |
+
|
22 |
+
from ._common import weekday as weekdaybase
|
23 |
+
|
24 |
+
try:
|
25 |
+
from math import gcd
|
26 |
+
except ImportError:
|
27 |
+
from fractions import gcd
|
28 |
+
|
29 |
+
__all__ = ["rrule", "rruleset", "rrulestr",
|
30 |
+
"YEARLY", "MONTHLY", "WEEKLY", "DAILY",
|
31 |
+
"HOURLY", "MINUTELY", "SECONDLY",
|
32 |
+
"MO", "TU", "WE", "TH", "FR", "SA", "SU"]
|
33 |
+
|
34 |
+
# Every mask is 7 days longer to handle cross-year weekly periods.
|
35 |
+
M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 +
|
36 |
+
[7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7)
|
37 |
+
M365MASK = list(M366MASK)
|
38 |
+
M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32))
|
39 |
+
MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7])
|
40 |
+
MDAY365MASK = list(MDAY366MASK)
|
41 |
+
M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0))
|
42 |
+
NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7])
|
43 |
+
NMDAY365MASK = list(NMDAY366MASK)
|
44 |
+
M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366)
|
45 |
+
M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365)
|
46 |
+
WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55
|
47 |
+
del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31]
|
48 |
+
MDAY365MASK = tuple(MDAY365MASK)
|
49 |
+
M365MASK = tuple(M365MASK)
|
50 |
+
|
51 |
+
FREQNAMES = ['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY']
|
52 |
+
|
53 |
+
(YEARLY,
|
54 |
+
MONTHLY,
|
55 |
+
WEEKLY,
|
56 |
+
DAILY,
|
57 |
+
HOURLY,
|
58 |
+
MINUTELY,
|
59 |
+
SECONDLY) = list(range(7))
|
60 |
+
|
61 |
+
# Imported on demand.
|
62 |
+
easter = None
|
63 |
+
parser = None
|
64 |
+
|
65 |
+
|
66 |
+
class weekday(weekdaybase):
|
67 |
+
"""
|
68 |
+
This version of weekday does not allow n = 0.
|
69 |
+
"""
|
70 |
+
def __init__(self, wkday, n=None):
|
71 |
+
if n == 0:
|
72 |
+
raise ValueError("Can't create weekday with n==0")
|
73 |
+
|
74 |
+
super(weekday, self).__init__(wkday, n)
|
75 |
+
|
76 |
+
|
77 |
+
MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7))
|
78 |
+
|
79 |
+
|
80 |
+
def _invalidates_cache(f):
|
81 |
+
"""
|
82 |
+
Decorator for rruleset methods which may invalidate the
|
83 |
+
cached length.
|
84 |
+
"""
|
85 |
+
@wraps(f)
|
86 |
+
def inner_func(self, *args, **kwargs):
|
87 |
+
rv = f(self, *args, **kwargs)
|
88 |
+
self._invalidate_cache()
|
89 |
+
return rv
|
90 |
+
|
91 |
+
return inner_func
|
92 |
+
|
93 |
+
|
94 |
+
class rrulebase(object):
|
95 |
+
def __init__(self, cache=False):
|
96 |
+
if cache:
|
97 |
+
self._cache = []
|
98 |
+
self._cache_lock = _thread.allocate_lock()
|
99 |
+
self._invalidate_cache()
|
100 |
+
else:
|
101 |
+
self._cache = None
|
102 |
+
self._cache_complete = False
|
103 |
+
self._len = None
|
104 |
+
|
105 |
+
def __iter__(self):
|
106 |
+
if self._cache_complete:
|
107 |
+
return iter(self._cache)
|
108 |
+
elif self._cache is None:
|
109 |
+
return self._iter()
|
110 |
+
else:
|
111 |
+
return self._iter_cached()
|
112 |
+
|
113 |
+
def _invalidate_cache(self):
|
114 |
+
if self._cache is not None:
|
115 |
+
self._cache = []
|
116 |
+
self._cache_complete = False
|
117 |
+
self._cache_gen = self._iter()
|
118 |
+
|
119 |
+
if self._cache_lock.locked():
|
120 |
+
self._cache_lock.release()
|
121 |
+
|
122 |
+
self._len = None
|
123 |
+
|
124 |
+
def _iter_cached(self):
|
125 |
+
i = 0
|
126 |
+
gen = self._cache_gen
|
127 |
+
cache = self._cache
|
128 |
+
acquire = self._cache_lock.acquire
|
129 |
+
release = self._cache_lock.release
|
130 |
+
while gen:
|
131 |
+
if i == len(cache):
|
132 |
+
acquire()
|
133 |
+
if self._cache_complete:
|
134 |
+
break
|
135 |
+
try:
|
136 |
+
for j in range(10):
|
137 |
+
cache.append(advance_iterator(gen))
|
138 |
+
except StopIteration:
|
139 |
+
self._cache_gen = gen = None
|
140 |
+
self._cache_complete = True
|
141 |
+
break
|
142 |
+
release()
|
143 |
+
yield cache[i]
|
144 |
+
i += 1
|
145 |
+
while i < self._len:
|
146 |
+
yield cache[i]
|
147 |
+
i += 1
|
148 |
+
|
149 |
+
def __getitem__(self, item):
|
150 |
+
if self._cache_complete:
|
151 |
+
return self._cache[item]
|
152 |
+
elif isinstance(item, slice):
|
153 |
+
if item.step and item.step < 0:
|
154 |
+
return list(iter(self))[item]
|
155 |
+
else:
|
156 |
+
return list(itertools.islice(self,
|
157 |
+
item.start or 0,
|
158 |
+
item.stop or sys.maxsize,
|
159 |
+
item.step or 1))
|
160 |
+
elif item >= 0:
|
161 |
+
gen = iter(self)
|
162 |
+
try:
|
163 |
+
for i in range(item+1):
|
164 |
+
res = advance_iterator(gen)
|
165 |
+
except StopIteration:
|
166 |
+
raise IndexError
|
167 |
+
return res
|
168 |
+
else:
|
169 |
+
return list(iter(self))[item]
|
170 |
+
|
171 |
+
def __contains__(self, item):
|
172 |
+
if self._cache_complete:
|
173 |
+
return item in self._cache
|
174 |
+
else:
|
175 |
+
for i in self:
|
176 |
+
if i == item:
|
177 |
+
return True
|
178 |
+
elif i > item:
|
179 |
+
return False
|
180 |
+
return False
|
181 |
+
|
182 |
+
# __len__() introduces a large performance penalty.
|
183 |
+
def count(self):
|
184 |
+
""" Returns the number of recurrences in this set. It will have go
|
185 |
+
through the whole recurrence, if this hasn't been done before. """
|
186 |
+
if self._len is None:
|
187 |
+
for x in self:
|
188 |
+
pass
|
189 |
+
return self._len
|
190 |
+
|
191 |
+
def before(self, dt, inc=False):
|
192 |
+
""" Returns the last recurrence before the given datetime instance. The
|
193 |
+
inc keyword defines what happens if dt is an occurrence. With
|
194 |
+
inc=True, if dt itself is an occurrence, it will be returned. """
|
195 |
+
if self._cache_complete:
|
196 |
+
gen = self._cache
|
197 |
+
else:
|
198 |
+
gen = self
|
199 |
+
last = None
|
200 |
+
if inc:
|
201 |
+
for i in gen:
|
202 |
+
if i > dt:
|
203 |
+
break
|
204 |
+
last = i
|
205 |
+
else:
|
206 |
+
for i in gen:
|
207 |
+
if i >= dt:
|
208 |
+
break
|
209 |
+
last = i
|
210 |
+
return last
|
211 |
+
|
212 |
+
def after(self, dt, inc=False):
|
213 |
+
""" Returns the first recurrence after the given datetime instance. The
|
214 |
+
inc keyword defines what happens if dt is an occurrence. With
|
215 |
+
inc=True, if dt itself is an occurrence, it will be returned. """
|
216 |
+
if self._cache_complete:
|
217 |
+
gen = self._cache
|
218 |
+
else:
|
219 |
+
gen = self
|
220 |
+
if inc:
|
221 |
+
for i in gen:
|
222 |
+
if i >= dt:
|
223 |
+
return i
|
224 |
+
else:
|
225 |
+
for i in gen:
|
226 |
+
if i > dt:
|
227 |
+
return i
|
228 |
+
return None
|
229 |
+
|
230 |
+
def xafter(self, dt, count=None, inc=False):
|
231 |
+
"""
|
232 |
+
Generator which yields up to `count` recurrences after the given
|
233 |
+
datetime instance, equivalent to `after`.
|
234 |
+
|
235 |
+
:param dt:
|
236 |
+
The datetime at which to start generating recurrences.
|
237 |
+
|
238 |
+
:param count:
|
239 |
+
The maximum number of recurrences to generate. If `None` (default),
|
240 |
+
dates are generated until the recurrence rule is exhausted.
|
241 |
+
|
242 |
+
:param inc:
|
243 |
+
If `dt` is an instance of the rule and `inc` is `True`, it is
|
244 |
+
included in the output.
|
245 |
+
|
246 |
+
:yields: Yields a sequence of `datetime` objects.
|
247 |
+
"""
|
248 |
+
|
249 |
+
if self._cache_complete:
|
250 |
+
gen = self._cache
|
251 |
+
else:
|
252 |
+
gen = self
|
253 |
+
|
254 |
+
# Select the comparison function
|
255 |
+
if inc:
|
256 |
+
comp = lambda dc, dtc: dc >= dtc
|
257 |
+
else:
|
258 |
+
comp = lambda dc, dtc: dc > dtc
|
259 |
+
|
260 |
+
# Generate dates
|
261 |
+
n = 0
|
262 |
+
for d in gen:
|
263 |
+
if comp(d, dt):
|
264 |
+
if count is not None:
|
265 |
+
n += 1
|
266 |
+
if n > count:
|
267 |
+
break
|
268 |
+
|
269 |
+
yield d
|
270 |
+
|
271 |
+
def between(self, after, before, inc=False, count=1):
|
272 |
+
""" Returns all the occurrences of the rrule between after and before.
|
273 |
+
The inc keyword defines what happens if after and/or before are
|
274 |
+
themselves occurrences. With inc=True, they will be included in the
|
275 |
+
list, if they are found in the recurrence set. """
|
276 |
+
if self._cache_complete:
|
277 |
+
gen = self._cache
|
278 |
+
else:
|
279 |
+
gen = self
|
280 |
+
started = False
|
281 |
+
l = []
|
282 |
+
if inc:
|
283 |
+
for i in gen:
|
284 |
+
if i > before:
|
285 |
+
break
|
286 |
+
elif not started:
|
287 |
+
if i >= after:
|
288 |
+
started = True
|
289 |
+
l.append(i)
|
290 |
+
else:
|
291 |
+
l.append(i)
|
292 |
+
else:
|
293 |
+
for i in gen:
|
294 |
+
if i >= before:
|
295 |
+
break
|
296 |
+
elif not started:
|
297 |
+
if i > after:
|
298 |
+
started = True
|
299 |
+
l.append(i)
|
300 |
+
else:
|
301 |
+
l.append(i)
|
302 |
+
return l
|
303 |
+
|
304 |
+
|
305 |
+
class rrule(rrulebase):
|
306 |
+
"""
|
307 |
+
That's the base of the rrule operation. It accepts all the keywords
|
308 |
+
defined in the RFC as its constructor parameters (except byday,
|
309 |
+
which was renamed to byweekday) and more. The constructor prototype is::
|
310 |
+
|
311 |
+
rrule(freq)
|
312 |
+
|
313 |
+
Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
|
314 |
+
or SECONDLY.
|
315 |
+
|
316 |
+
.. note::
|
317 |
+
Per RFC section 3.3.10, recurrence instances falling on invalid dates
|
318 |
+
and times are ignored rather than coerced:
|
319 |
+
|
320 |
+
Recurrence rules may generate recurrence instances with an invalid
|
321 |
+
date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM
|
322 |
+
on a day where the local time is moved forward by an hour at 1:00
|
323 |
+
AM). Such recurrence instances MUST be ignored and MUST NOT be
|
324 |
+
counted as part of the recurrence set.
|
325 |
+
|
326 |
+
This can lead to possibly surprising behavior when, for example, the
|
327 |
+
start date occurs at the end of the month:
|
328 |
+
|
329 |
+
>>> from dateutil.rrule import rrule, MONTHLY
|
330 |
+
>>> from datetime import datetime
|
331 |
+
>>> start_date = datetime(2014, 12, 31)
|
332 |
+
>>> list(rrule(freq=MONTHLY, count=4, dtstart=start_date))
|
333 |
+
... # doctest: +NORMALIZE_WHITESPACE
|
334 |
+
[datetime.datetime(2014, 12, 31, 0, 0),
|
335 |
+
datetime.datetime(2015, 1, 31, 0, 0),
|
336 |
+
datetime.datetime(2015, 3, 31, 0, 0),
|
337 |
+
datetime.datetime(2015, 5, 31, 0, 0)]
|
338 |
+
|
339 |
+
Additionally, it supports the following keyword arguments:
|
340 |
+
|
341 |
+
:param dtstart:
|
342 |
+
The recurrence start. Besides being the base for the recurrence,
|
343 |
+
missing parameters in the final recurrence instances will also be
|
344 |
+
extracted from this date. If not given, datetime.now() will be used
|
345 |
+
instead.
|
346 |
+
:param interval:
|
347 |
+
The interval between each freq iteration. For example, when using
|
348 |
+
YEARLY, an interval of 2 means once every two years, but with HOURLY,
|
349 |
+
it means once every two hours. The default interval is 1.
|
350 |
+
:param wkst:
|
351 |
+
The week start day. Must be one of the MO, TU, WE constants, or an
|
352 |
+
integer, specifying the first day of the week. This will affect
|
353 |
+
recurrences based on weekly periods. The default week start is got
|
354 |
+
from calendar.firstweekday(), and may be modified by
|
355 |
+
calendar.setfirstweekday().
|
356 |
+
:param count:
|
357 |
+
If given, this determines how many occurrences will be generated.
|
358 |
+
|
359 |
+
.. note::
|
360 |
+
As of version 2.5.0, the use of the keyword ``until`` in conjunction
|
361 |
+
with ``count`` is deprecated, to make sure ``dateutil`` is fully
|
362 |
+
compliant with `RFC-5545 Sec. 3.3.10 <https://tools.ietf.org/
|
363 |
+
html/rfc5545#section-3.3.10>`_. Therefore, ``until`` and ``count``
|
364 |
+
**must not** occur in the same call to ``rrule``.
|
365 |
+
:param until:
|
366 |
+
If given, this must be a datetime instance specifying the upper-bound
|
367 |
+
limit of the recurrence. The last recurrence in the rule is the greatest
|
368 |
+
datetime that is less than or equal to the value specified in the
|
369 |
+
``until`` parameter.
|
370 |
+
|
371 |
+
.. note::
|
372 |
+
As of version 2.5.0, the use of the keyword ``until`` in conjunction
|
373 |
+
with ``count`` is deprecated, to make sure ``dateutil`` is fully
|
374 |
+
compliant with `RFC-5545 Sec. 3.3.10 <https://tools.ietf.org/
|
375 |
+
html/rfc5545#section-3.3.10>`_. Therefore, ``until`` and ``count``
|
376 |
+
**must not** occur in the same call to ``rrule``.
|
377 |
+
:param bysetpos:
|
378 |
+
If given, it must be either an integer, or a sequence of integers,
|
379 |
+
positive or negative. Each given integer will specify an occurrence
|
380 |
+
number, corresponding to the nth occurrence of the rule inside the
|
381 |
+
frequency period. For example, a bysetpos of -1 if combined with a
|
382 |
+
MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will
|
383 |
+
result in the last work day of every month.
|
384 |
+
:param bymonth:
|
385 |
+
If given, it must be either an integer, or a sequence of integers,
|
386 |
+
meaning the months to apply the recurrence to.
|
387 |
+
:param bymonthday:
|
388 |
+
If given, it must be either an integer, or a sequence of integers,
|
389 |
+
meaning the month days to apply the recurrence to.
|
390 |
+
:param byyearday:
|
391 |
+
If given, it must be either an integer, or a sequence of integers,
|
392 |
+
meaning the year days to apply the recurrence to.
|
393 |
+
:param byeaster:
|
394 |
+
If given, it must be either an integer, or a sequence of integers,
|
395 |
+
positive or negative. Each integer will define an offset from the
|
396 |
+
Easter Sunday. Passing the offset 0 to byeaster will yield the Easter
|
397 |
+
Sunday itself. This is an extension to the RFC specification.
|
398 |
+
:param byweekno:
|
399 |
+
If given, it must be either an integer, or a sequence of integers,
|
400 |
+
meaning the week numbers to apply the recurrence to. Week numbers
|
401 |
+
have the meaning described in ISO8601, that is, the first week of
|
402 |
+
the year is that containing at least four days of the new year.
|
403 |
+
:param byweekday:
|
404 |
+
If given, it must be either an integer (0 == MO), a sequence of
|
405 |
+
integers, one of the weekday constants (MO, TU, etc), or a sequence
|
406 |
+
of these constants. When given, these variables will define the
|
407 |
+
weekdays where the recurrence will be applied. It's also possible to
|
408 |
+
use an argument n for the weekday instances, which will mean the nth
|
409 |
+
occurrence of this weekday in the period. For example, with MONTHLY,
|
410 |
+
or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the
|
411 |
+
first friday of the month where the recurrence happens. Notice that in
|
412 |
+
the RFC documentation, this is specified as BYDAY, but was renamed to
|
413 |
+
avoid the ambiguity of that keyword.
|
414 |
+
:param byhour:
|
415 |
+
If given, it must be either an integer, or a sequence of integers,
|
416 |
+
meaning the hours to apply the recurrence to.
|
417 |
+
:param byminute:
|
418 |
+
If given, it must be either an integer, or a sequence of integers,
|
419 |
+
meaning the minutes to apply the recurrence to.
|
420 |
+
:param bysecond:
|
421 |
+
If given, it must be either an integer, or a sequence of integers,
|
422 |
+
meaning the seconds to apply the recurrence to.
|
423 |
+
:param cache:
|
424 |
+
If given, it must be a boolean value specifying to enable or disable
|
425 |
+
caching of results. If you will use the same rrule instance multiple
|
426 |
+
times, enabling caching will improve the performance considerably.
|
427 |
+
"""
|
428 |
+
def __init__(self, freq, dtstart=None,
|
429 |
+
interval=1, wkst=None, count=None, until=None, bysetpos=None,
|
430 |
+
bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
|
431 |
+
byweekno=None, byweekday=None,
|
432 |
+
byhour=None, byminute=None, bysecond=None,
|
433 |
+
cache=False):
|
434 |
+
super(rrule, self).__init__(cache)
|
435 |
+
global easter
|
436 |
+
if not dtstart:
|
437 |
+
if until and until.tzinfo:
|
438 |
+
dtstart = datetime.datetime.now(tz=until.tzinfo).replace(microsecond=0)
|
439 |
+
else:
|
440 |
+
dtstart = datetime.datetime.now().replace(microsecond=0)
|
441 |
+
elif not isinstance(dtstart, datetime.datetime):
|
442 |
+
dtstart = datetime.datetime.fromordinal(dtstart.toordinal())
|
443 |
+
else:
|
444 |
+
dtstart = dtstart.replace(microsecond=0)
|
445 |
+
self._dtstart = dtstart
|
446 |
+
self._tzinfo = dtstart.tzinfo
|
447 |
+
self._freq = freq
|
448 |
+
self._interval = interval
|
449 |
+
self._count = count
|
450 |
+
|
451 |
+
# Cache the original byxxx rules, if they are provided, as the _byxxx
|
452 |
+
# attributes do not necessarily map to the inputs, and this can be
|
453 |
+
# a problem in generating the strings. Only store things if they've
|
454 |
+
# been supplied (the string retrieval will just use .get())
|
455 |
+
self._original_rule = {}
|
456 |
+
|
457 |
+
if until and not isinstance(until, datetime.datetime):
|
458 |
+
until = datetime.datetime.fromordinal(until.toordinal())
|
459 |
+
self._until = until
|
460 |
+
|
461 |
+
if self._dtstart and self._until:
|
462 |
+
if (self._dtstart.tzinfo is not None) != (self._until.tzinfo is not None):
|
463 |
+
# According to RFC5545 Section 3.3.10:
|
464 |
+
# https://tools.ietf.org/html/rfc5545#section-3.3.10
|
465 |
+
#
|
466 |
+
# > If the "DTSTART" property is specified as a date with UTC
|
467 |
+
# > time or a date with local time and time zone reference,
|
468 |
+
# > then the UNTIL rule part MUST be specified as a date with
|
469 |
+
# > UTC time.
|
470 |
+
raise ValueError(
|
471 |
+
'RRULE UNTIL values must be specified in UTC when DTSTART '
|
472 |
+
'is timezone-aware'
|
473 |
+
)
|
474 |
+
|
475 |
+
if count is not None and until:
|
476 |
+
warn("Using both 'count' and 'until' is inconsistent with RFC 5545"
|
477 |
+
" and has been deprecated in dateutil. Future versions will "
|
478 |
+
"raise an error.", DeprecationWarning)
|
479 |
+
|
480 |
+
if wkst is None:
|
481 |
+
self._wkst = calendar.firstweekday()
|
482 |
+
elif isinstance(wkst, integer_types):
|
483 |
+
self._wkst = wkst
|
484 |
+
else:
|
485 |
+
self._wkst = wkst.weekday
|
486 |
+
|
487 |
+
if bysetpos is None:
|
488 |
+
self._bysetpos = None
|
489 |
+
elif isinstance(bysetpos, integer_types):
|
490 |
+
if bysetpos == 0 or not (-366 <= bysetpos <= 366):
|
491 |
+
raise ValueError("bysetpos must be between 1 and 366, "
|
492 |
+
"or between -366 and -1")
|
493 |
+
self._bysetpos = (bysetpos,)
|
494 |
+
else:
|
495 |
+
self._bysetpos = tuple(bysetpos)
|
496 |
+
for pos in self._bysetpos:
|
497 |
+
if pos == 0 or not (-366 <= pos <= 366):
|
498 |
+
raise ValueError("bysetpos must be between 1 and 366, "
|
499 |
+
"or between -366 and -1")
|
500 |
+
|
501 |
+
if self._bysetpos:
|
502 |
+
self._original_rule['bysetpos'] = self._bysetpos
|
503 |
+
|
504 |
+
if (byweekno is None and byyearday is None and bymonthday is None and
|
505 |
+
byweekday is None and byeaster is None):
|
506 |
+
if freq == YEARLY:
|
507 |
+
if bymonth is None:
|
508 |
+
bymonth = dtstart.month
|
509 |
+
self._original_rule['bymonth'] = None
|
510 |
+
bymonthday = dtstart.day
|
511 |
+
self._original_rule['bymonthday'] = None
|
512 |
+
elif freq == MONTHLY:
|
513 |
+
bymonthday = dtstart.day
|
514 |
+
self._original_rule['bymonthday'] = None
|
515 |
+
elif freq == WEEKLY:
|
516 |
+
byweekday = dtstart.weekday()
|
517 |
+
self._original_rule['byweekday'] = None
|
518 |
+
|
519 |
+
# bymonth
|
520 |
+
if bymonth is None:
|
521 |
+
self._bymonth = None
|
522 |
+
else:
|
523 |
+
if isinstance(bymonth, integer_types):
|
524 |
+
bymonth = (bymonth,)
|
525 |
+
|
526 |
+
self._bymonth = tuple(sorted(set(bymonth)))
|
527 |
+
|
528 |
+
if 'bymonth' not in self._original_rule:
|
529 |
+
self._original_rule['bymonth'] = self._bymonth
|
530 |
+
|
531 |
+
# byyearday
|
532 |
+
if byyearday is None:
|
533 |
+
self._byyearday = None
|
534 |
+
else:
|
535 |
+
if isinstance(byyearday, integer_types):
|
536 |
+
byyearday = (byyearday,)
|
537 |
+
|
538 |
+
self._byyearday = tuple(sorted(set(byyearday)))
|
539 |
+
self._original_rule['byyearday'] = self._byyearday
|
540 |
+
|
541 |
+
# byeaster
|
542 |
+
if byeaster is not None:
|
543 |
+
if not easter:
|
544 |
+
from dateutil import easter
|
545 |
+
if isinstance(byeaster, integer_types):
|
546 |
+
self._byeaster = (byeaster,)
|
547 |
+
else:
|
548 |
+
self._byeaster = tuple(sorted(byeaster))
|
549 |
+
|
550 |
+
self._original_rule['byeaster'] = self._byeaster
|
551 |
+
else:
|
552 |
+
self._byeaster = None
|
553 |
+
|
554 |
+
# bymonthday
|
555 |
+
if bymonthday is None:
|
556 |
+
self._bymonthday = ()
|
557 |
+
self._bynmonthday = ()
|
558 |
+
else:
|
559 |
+
if isinstance(bymonthday, integer_types):
|
560 |
+
bymonthday = (bymonthday,)
|
561 |
+
|
562 |
+
bymonthday = set(bymonthday) # Ensure it's unique
|
563 |
+
|
564 |
+
self._bymonthday = tuple(sorted(x for x in bymonthday if x > 0))
|
565 |
+
self._bynmonthday = tuple(sorted(x for x in bymonthday if x < 0))
|
566 |
+
|
567 |
+
# Storing positive numbers first, then negative numbers
|
568 |
+
if 'bymonthday' not in self._original_rule:
|
569 |
+
self._original_rule['bymonthday'] = tuple(
|
570 |
+
itertools.chain(self._bymonthday, self._bynmonthday))
|
571 |
+
|
572 |
+
# byweekno
|
573 |
+
if byweekno is None:
|
574 |
+
self._byweekno = None
|
575 |
+
else:
|
576 |
+
if isinstance(byweekno, integer_types):
|
577 |
+
byweekno = (byweekno,)
|
578 |
+
|
579 |
+
self._byweekno = tuple(sorted(set(byweekno)))
|
580 |
+
|
581 |
+
self._original_rule['byweekno'] = self._byweekno
|
582 |
+
|
583 |
+
# byweekday / bynweekday
|
584 |
+
if byweekday is None:
|
585 |
+
self._byweekday = None
|
586 |
+
self._bynweekday = None
|
587 |
+
else:
|
588 |
+
# If it's one of the valid non-sequence types, convert to a
|
589 |
+
# single-element sequence before the iterator that builds the
|
590 |
+
# byweekday set.
|
591 |
+
if isinstance(byweekday, integer_types) or hasattr(byweekday, "n"):
|
592 |
+
byweekday = (byweekday,)
|
593 |
+
|
594 |
+
self._byweekday = set()
|
595 |
+
self._bynweekday = set()
|
596 |
+
for wday in byweekday:
|
597 |
+
if isinstance(wday, integer_types):
|
598 |
+
self._byweekday.add(wday)
|
599 |
+
elif not wday.n or freq > MONTHLY:
|
600 |
+
self._byweekday.add(wday.weekday)
|
601 |
+
else:
|
602 |
+
self._bynweekday.add((wday.weekday, wday.n))
|
603 |
+
|
604 |
+
if not self._byweekday:
|
605 |
+
self._byweekday = None
|
606 |
+
elif not self._bynweekday:
|
607 |
+
self._bynweekday = None
|
608 |
+
|
609 |
+
if self._byweekday is not None:
|
610 |
+
self._byweekday = tuple(sorted(self._byweekday))
|
611 |
+
orig_byweekday = [weekday(x) for x in self._byweekday]
|
612 |
+
else:
|
613 |
+
orig_byweekday = ()
|
614 |
+
|
615 |
+
if self._bynweekday is not None:
|
616 |
+
self._bynweekday = tuple(sorted(self._bynweekday))
|
617 |
+
orig_bynweekday = [weekday(*x) for x in self._bynweekday]
|
618 |
+
else:
|
619 |
+
orig_bynweekday = ()
|
620 |
+
|
621 |
+
if 'byweekday' not in self._original_rule:
|
622 |
+
self._original_rule['byweekday'] = tuple(itertools.chain(
|
623 |
+
orig_byweekday, orig_bynweekday))
|
624 |
+
|
625 |
+
# byhour
|
626 |
+
if byhour is None:
|
627 |
+
if freq < HOURLY:
|
628 |
+
self._byhour = {dtstart.hour}
|
629 |
+
else:
|
630 |
+
self._byhour = None
|
631 |
+
else:
|
632 |
+
if isinstance(byhour, integer_types):
|
633 |
+
byhour = (byhour,)
|
634 |
+
|
635 |
+
if freq == HOURLY:
|
636 |
+
self._byhour = self.__construct_byset(start=dtstart.hour,
|
637 |
+
byxxx=byhour,
|
638 |
+
base=24)
|
639 |
+
else:
|
640 |
+
self._byhour = set(byhour)
|
641 |
+
|
642 |
+
self._byhour = tuple(sorted(self._byhour))
|
643 |
+
self._original_rule['byhour'] = self._byhour
|
644 |
+
|
645 |
+
# byminute
|
646 |
+
if byminute is None:
|
647 |
+
if freq < MINUTELY:
|
648 |
+
self._byminute = {dtstart.minute}
|
649 |
+
else:
|
650 |
+
self._byminute = None
|
651 |
+
else:
|
652 |
+
if isinstance(byminute, integer_types):
|
653 |
+
byminute = (byminute,)
|
654 |
+
|
655 |
+
if freq == MINUTELY:
|
656 |
+
self._byminute = self.__construct_byset(start=dtstart.minute,
|
657 |
+
byxxx=byminute,
|
658 |
+
base=60)
|
659 |
+
else:
|
660 |
+
self._byminute = set(byminute)
|
661 |
+
|
662 |
+
self._byminute = tuple(sorted(self._byminute))
|
663 |
+
self._original_rule['byminute'] = self._byminute
|
664 |
+
|
665 |
+
# bysecond
|
666 |
+
if bysecond is None:
|
667 |
+
if freq < SECONDLY:
|
668 |
+
self._bysecond = ((dtstart.second,))
|
669 |
+
else:
|
670 |
+
self._bysecond = None
|
671 |
+
else:
|
672 |
+
if isinstance(bysecond, integer_types):
|
673 |
+
bysecond = (bysecond,)
|
674 |
+
|
675 |
+
self._bysecond = set(bysecond)
|
676 |
+
|
677 |
+
if freq == SECONDLY:
|
678 |
+
self._bysecond = self.__construct_byset(start=dtstart.second,
|
679 |
+
byxxx=bysecond,
|
680 |
+
base=60)
|
681 |
+
else:
|
682 |
+
self._bysecond = set(bysecond)
|
683 |
+
|
684 |
+
self._bysecond = tuple(sorted(self._bysecond))
|
685 |
+
self._original_rule['bysecond'] = self._bysecond
|
686 |
+
|
687 |
+
if self._freq >= HOURLY:
|
688 |
+
self._timeset = None
|
689 |
+
else:
|
690 |
+
self._timeset = []
|
691 |
+
for hour in self._byhour:
|
692 |
+
for minute in self._byminute:
|
693 |
+
for second in self._bysecond:
|
694 |
+
self._timeset.append(
|
695 |
+
datetime.time(hour, minute, second,
|
696 |
+
tzinfo=self._tzinfo))
|
697 |
+
self._timeset.sort()
|
698 |
+
self._timeset = tuple(self._timeset)
|
699 |
+
|
700 |
+
def __str__(self):
|
701 |
+
"""
|
702 |
+
Output a string that would generate this RRULE if passed to rrulestr.
|
703 |
+
This is mostly compatible with RFC5545, except for the
|
704 |
+
dateutil-specific extension BYEASTER.
|
705 |
+
"""
|
706 |
+
|
707 |
+
output = []
|
708 |
+
h, m, s = [None] * 3
|
709 |
+
if self._dtstart:
|
710 |
+
output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S'))
|
711 |
+
h, m, s = self._dtstart.timetuple()[3:6]
|
712 |
+
|
713 |
+
parts = ['FREQ=' + FREQNAMES[self._freq]]
|
714 |
+
if self._interval != 1:
|
715 |
+
parts.append('INTERVAL=' + str(self._interval))
|
716 |
+
|
717 |
+
if self._wkst:
|
718 |
+
parts.append('WKST=' + repr(weekday(self._wkst))[0:2])
|
719 |
+
|
720 |
+
if self._count is not None:
|
721 |
+
parts.append('COUNT=' + str(self._count))
|
722 |
+
|
723 |
+
if self._until:
|
724 |
+
parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S'))
|
725 |
+
|
726 |
+
if self._original_rule.get('byweekday') is not None:
|
727 |
+
# The str() method on weekday objects doesn't generate
|
728 |
+
# RFC5545-compliant strings, so we should modify that.
|
729 |
+
original_rule = dict(self._original_rule)
|
730 |
+
wday_strings = []
|
731 |
+
for wday in original_rule['byweekday']:
|
732 |
+
if wday.n:
|
733 |
+
wday_strings.append('{n:+d}{wday}'.format(
|
734 |
+
n=wday.n,
|
735 |
+
wday=repr(wday)[0:2]))
|
736 |
+
else:
|
737 |
+
wday_strings.append(repr(wday))
|
738 |
+
|
739 |
+
original_rule['byweekday'] = wday_strings
|
740 |
+
else:
|
741 |
+
original_rule = self._original_rule
|
742 |
+
|
743 |
+
partfmt = '{name}={vals}'
|
744 |
+
for name, key in [('BYSETPOS', 'bysetpos'),
|
745 |
+
('BYMONTH', 'bymonth'),
|
746 |
+
('BYMONTHDAY', 'bymonthday'),
|
747 |
+
('BYYEARDAY', 'byyearday'),
|
748 |
+
('BYWEEKNO', 'byweekno'),
|
749 |
+
('BYDAY', 'byweekday'),
|
750 |
+
('BYHOUR', 'byhour'),
|
751 |
+
('BYMINUTE', 'byminute'),
|
752 |
+
('BYSECOND', 'bysecond'),
|
753 |
+
('BYEASTER', 'byeaster')]:
|
754 |
+
value = original_rule.get(key)
|
755 |
+
if value:
|
756 |
+
parts.append(partfmt.format(name=name, vals=(','.join(str(v)
|
757 |
+
for v in value))))
|
758 |
+
|
759 |
+
output.append('RRULE:' + ';'.join(parts))
|
760 |
+
return '\n'.join(output)
|
761 |
+
|
762 |
+
def replace(self, **kwargs):
|
763 |
+
"""Return new rrule with same attributes except for those attributes given new
|
764 |
+
values by whichever keyword arguments are specified."""
|
765 |
+
new_kwargs = {"interval": self._interval,
|
766 |
+
"count": self._count,
|
767 |
+
"dtstart": self._dtstart,
|
768 |
+
"freq": self._freq,
|
769 |
+
"until": self._until,
|
770 |
+
"wkst": self._wkst,
|
771 |
+
"cache": False if self._cache is None else True }
|
772 |
+
new_kwargs.update(self._original_rule)
|
773 |
+
new_kwargs.update(kwargs)
|
774 |
+
return rrule(**new_kwargs)
|
775 |
+
|
776 |
+
def _iter(self):
|
777 |
+
year, month, day, hour, minute, second, weekday, yearday, _ = \
|
778 |
+
self._dtstart.timetuple()
|
779 |
+
|
780 |
+
# Some local variables to speed things up a bit
|
781 |
+
freq = self._freq
|
782 |
+
interval = self._interval
|
783 |
+
wkst = self._wkst
|
784 |
+
until = self._until
|
785 |
+
bymonth = self._bymonth
|
786 |
+
byweekno = self._byweekno
|
787 |
+
byyearday = self._byyearday
|
788 |
+
byweekday = self._byweekday
|
789 |
+
byeaster = self._byeaster
|
790 |
+
bymonthday = self._bymonthday
|
791 |
+
bynmonthday = self._bynmonthday
|
792 |
+
bysetpos = self._bysetpos
|
793 |
+
byhour = self._byhour
|
794 |
+
byminute = self._byminute
|
795 |
+
bysecond = self._bysecond
|
796 |
+
|
797 |
+
ii = _iterinfo(self)
|
798 |
+
ii.rebuild(year, month)
|
799 |
+
|
800 |
+
getdayset = {YEARLY: ii.ydayset,
|
801 |
+
MONTHLY: ii.mdayset,
|
802 |
+
WEEKLY: ii.wdayset,
|
803 |
+
DAILY: ii.ddayset,
|
804 |
+
HOURLY: ii.ddayset,
|
805 |
+
MINUTELY: ii.ddayset,
|
806 |
+
SECONDLY: ii.ddayset}[freq]
|
807 |
+
|
808 |
+
if freq < HOURLY:
|
809 |
+
timeset = self._timeset
|
810 |
+
else:
|
811 |
+
gettimeset = {HOURLY: ii.htimeset,
|
812 |
+
MINUTELY: ii.mtimeset,
|
813 |
+
SECONDLY: ii.stimeset}[freq]
|
814 |
+
if ((freq >= HOURLY and
|
815 |
+
self._byhour and hour not in self._byhour) or
|
816 |
+
(freq >= MINUTELY and
|
817 |
+
self._byminute and minute not in self._byminute) or
|
818 |
+
(freq >= SECONDLY and
|
819 |
+
self._bysecond and second not in self._bysecond)):
|
820 |
+
timeset = ()
|
821 |
+
else:
|
822 |
+
timeset = gettimeset(hour, minute, second)
|
823 |
+
|
824 |
+
total = 0
|
825 |
+
count = self._count
|
826 |
+
while True:
|
827 |
+
# Get dayset with the right frequency
|
828 |
+
dayset, start, end = getdayset(year, month, day)
|
829 |
+
|
830 |
+
# Do the "hard" work ;-)
|
831 |
+
filtered = False
|
832 |
+
for i in dayset[start:end]:
|
833 |
+
if ((bymonth and ii.mmask[i] not in bymonth) or
|
834 |
+
(byweekno and not ii.wnomask[i]) or
|
835 |
+
(byweekday and ii.wdaymask[i] not in byweekday) or
|
836 |
+
(ii.nwdaymask and not ii.nwdaymask[i]) or
|
837 |
+
(byeaster and not ii.eastermask[i]) or
|
838 |
+
((bymonthday or bynmonthday) and
|
839 |
+
ii.mdaymask[i] not in bymonthday and
|
840 |
+
ii.nmdaymask[i] not in bynmonthday) or
|
841 |
+
(byyearday and
|
842 |
+
((i < ii.yearlen and i+1 not in byyearday and
|
843 |
+
-ii.yearlen+i not in byyearday) or
|
844 |
+
(i >= ii.yearlen and i+1-ii.yearlen not in byyearday and
|
845 |
+
-ii.nextyearlen+i-ii.yearlen not in byyearday)))):
|
846 |
+
dayset[i] = None
|
847 |
+
filtered = True
|
848 |
+
|
849 |
+
# Output results
|
850 |
+
if bysetpos and timeset:
|
851 |
+
poslist = []
|
852 |
+
for pos in bysetpos:
|
853 |
+
if pos < 0:
|
854 |
+
daypos, timepos = divmod(pos, len(timeset))
|
855 |
+
else:
|
856 |
+
daypos, timepos = divmod(pos-1, len(timeset))
|
857 |
+
try:
|
858 |
+
i = [x for x in dayset[start:end]
|
859 |
+
if x is not None][daypos]
|
860 |
+
time = timeset[timepos]
|
861 |
+
except IndexError:
|
862 |
+
pass
|
863 |
+
else:
|
864 |
+
date = datetime.date.fromordinal(ii.yearordinal+i)
|
865 |
+
res = datetime.datetime.combine(date, time)
|
866 |
+
if res not in poslist:
|
867 |
+
poslist.append(res)
|
868 |
+
poslist.sort()
|
869 |
+
for res in poslist:
|
870 |
+
if until and res > until:
|
871 |
+
self._len = total
|
872 |
+
return
|
873 |
+
elif res >= self._dtstart:
|
874 |
+
if count is not None:
|
875 |
+
count -= 1
|
876 |
+
if count < 0:
|
877 |
+
self._len = total
|
878 |
+
return
|
879 |
+
total += 1
|
880 |
+
yield res
|
881 |
+
else:
|
882 |
+
for i in dayset[start:end]:
|
883 |
+
if i is not None:
|
884 |
+
date = datetime.date.fromordinal(ii.yearordinal + i)
|
885 |
+
for time in timeset:
|
886 |
+
res = datetime.datetime.combine(date, time)
|
887 |
+
if until and res > until:
|
888 |
+
self._len = total
|
889 |
+
return
|
890 |
+
elif res >= self._dtstart:
|
891 |
+
if count is not None:
|
892 |
+
count -= 1
|
893 |
+
if count < 0:
|
894 |
+
self._len = total
|
895 |
+
return
|
896 |
+
|
897 |
+
total += 1
|
898 |
+
yield res
|
899 |
+
|
900 |
+
# Handle frequency and interval
|
901 |
+
fixday = False
|
902 |
+
if freq == YEARLY:
|
903 |
+
year += interval
|
904 |
+
if year > datetime.MAXYEAR:
|
905 |
+
self._len = total
|
906 |
+
return
|
907 |
+
ii.rebuild(year, month)
|
908 |
+
elif freq == MONTHLY:
|
909 |
+
month += interval
|
910 |
+
if month > 12:
|
911 |
+
div, mod = divmod(month, 12)
|
912 |
+
month = mod
|
913 |
+
year += div
|
914 |
+
if month == 0:
|
915 |
+
month = 12
|
916 |
+
year -= 1
|
917 |
+
if year > datetime.MAXYEAR:
|
918 |
+
self._len = total
|
919 |
+
return
|
920 |
+
ii.rebuild(year, month)
|
921 |
+
elif freq == WEEKLY:
|
922 |
+
if wkst > weekday:
|
923 |
+
day += -(weekday+1+(6-wkst))+self._interval*7
|
924 |
+
else:
|
925 |
+
day += -(weekday-wkst)+self._interval*7
|
926 |
+
weekday = wkst
|
927 |
+
fixday = True
|
928 |
+
elif freq == DAILY:
|
929 |
+
day += interval
|
930 |
+
fixday = True
|
931 |
+
elif freq == HOURLY:
|
932 |
+
if filtered:
|
933 |
+
# Jump to one iteration before next day
|
934 |
+
hour += ((23-hour)//interval)*interval
|
935 |
+
|
936 |
+
if byhour:
|
937 |
+
ndays, hour = self.__mod_distance(value=hour,
|
938 |
+
byxxx=self._byhour,
|
939 |
+
base=24)
|
940 |
+
else:
|
941 |
+
ndays, hour = divmod(hour+interval, 24)
|
942 |
+
|
943 |
+
if ndays:
|
944 |
+
day += ndays
|
945 |
+
fixday = True
|
946 |
+
|
947 |
+
timeset = gettimeset(hour, minute, second)
|
948 |
+
elif freq == MINUTELY:
|
949 |
+
if filtered:
|
950 |
+
# Jump to one iteration before next day
|
951 |
+
minute += ((1439-(hour*60+minute))//interval)*interval
|
952 |
+
|
953 |
+
valid = False
|
954 |
+
rep_rate = (24*60)
|
955 |
+
for j in range(rep_rate // gcd(interval, rep_rate)):
|
956 |
+
if byminute:
|
957 |
+
nhours, minute = \
|
958 |
+
self.__mod_distance(value=minute,
|
959 |
+
byxxx=self._byminute,
|
960 |
+
base=60)
|
961 |
+
else:
|
962 |
+
nhours, minute = divmod(minute+interval, 60)
|
963 |
+
|
964 |
+
div, hour = divmod(hour+nhours, 24)
|
965 |
+
if div:
|
966 |
+
day += div
|
967 |
+
fixday = True
|
968 |
+
filtered = False
|
969 |
+
|
970 |
+
if not byhour or hour in byhour:
|
971 |
+
valid = True
|
972 |
+
break
|
973 |
+
|
974 |
+
if not valid:
|
975 |
+
raise ValueError('Invalid combination of interval and ' +
|
976 |
+
'byhour resulting in empty rule.')
|
977 |
+
|
978 |
+
timeset = gettimeset(hour, minute, second)
|
979 |
+
elif freq == SECONDLY:
|
980 |
+
if filtered:
|
981 |
+
# Jump to one iteration before next day
|
982 |
+
second += (((86399 - (hour * 3600 + minute * 60 + second))
|
983 |
+
// interval) * interval)
|
984 |
+
|
985 |
+
rep_rate = (24 * 3600)
|
986 |
+
valid = False
|
987 |
+
for j in range(0, rep_rate // gcd(interval, rep_rate)):
|
988 |
+
if bysecond:
|
989 |
+
nminutes, second = \
|
990 |
+
self.__mod_distance(value=second,
|
991 |
+
byxxx=self._bysecond,
|
992 |
+
base=60)
|
993 |
+
else:
|
994 |
+
nminutes, second = divmod(second+interval, 60)
|
995 |
+
|
996 |
+
div, minute = divmod(minute+nminutes, 60)
|
997 |
+
if div:
|
998 |
+
hour += div
|
999 |
+
div, hour = divmod(hour, 24)
|
1000 |
+
if div:
|
1001 |
+
day += div
|
1002 |
+
fixday = True
|
1003 |
+
|
1004 |
+
if ((not byhour or hour in byhour) and
|
1005 |
+
(not byminute or minute in byminute) and
|
1006 |
+
(not bysecond or second in bysecond)):
|
1007 |
+
valid = True
|
1008 |
+
break
|
1009 |
+
|
1010 |
+
if not valid:
|
1011 |
+
raise ValueError('Invalid combination of interval, ' +
|
1012 |
+
'byhour and byminute resulting in empty' +
|
1013 |
+
' rule.')
|
1014 |
+
|
1015 |
+
timeset = gettimeset(hour, minute, second)
|
1016 |
+
|
1017 |
+
if fixday and day > 28:
|
1018 |
+
daysinmonth = calendar.monthrange(year, month)[1]
|
1019 |
+
if day > daysinmonth:
|
1020 |
+
while day > daysinmonth:
|
1021 |
+
day -= daysinmonth
|
1022 |
+
month += 1
|
1023 |
+
if month == 13:
|
1024 |
+
month = 1
|
1025 |
+
year += 1
|
1026 |
+
if year > datetime.MAXYEAR:
|
1027 |
+
self._len = total
|
1028 |
+
return
|
1029 |
+
daysinmonth = calendar.monthrange(year, month)[1]
|
1030 |
+
ii.rebuild(year, month)
|
1031 |
+
|
1032 |
+
def __construct_byset(self, start, byxxx, base):
|
1033 |
+
"""
|
1034 |
+
If a `BYXXX` sequence is passed to the constructor at the same level as
|
1035 |
+
`FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some
|
1036 |
+
specifications which cannot be reached given some starting conditions.
|
1037 |
+
|
1038 |
+
This occurs whenever the interval is not coprime with the base of a
|
1039 |
+
given unit and the difference between the starting position and the
|
1040 |
+
ending position is not coprime with the greatest common denominator
|
1041 |
+
between the interval and the base. For example, with a FREQ of hourly
|
1042 |
+
starting at 17:00 and an interval of 4, the only valid values for
|
1043 |
+
BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not
|
1044 |
+
coprime.
|
1045 |
+
|
1046 |
+
:param start:
|
1047 |
+
Specifies the starting position.
|
1048 |
+
:param byxxx:
|
1049 |
+
An iterable containing the list of allowed values.
|
1050 |
+
:param base:
|
1051 |
+
The largest allowable value for the specified frequency (e.g.
|
1052 |
+
24 hours, 60 minutes).
|
1053 |
+
|
1054 |
+
This does not preserve the type of the iterable, returning a set, since
|
1055 |
+
the values should be unique and the order is irrelevant, this will
|
1056 |
+
speed up later lookups.
|
1057 |
+
|
1058 |
+
In the event of an empty set, raises a :exception:`ValueError`, as this
|
1059 |
+
results in an empty rrule.
|
1060 |
+
"""
|
1061 |
+
|
1062 |
+
cset = set()
|
1063 |
+
|
1064 |
+
# Support a single byxxx value.
|
1065 |
+
if isinstance(byxxx, integer_types):
|
1066 |
+
byxxx = (byxxx, )
|
1067 |
+
|
1068 |
+
for num in byxxx:
|
1069 |
+
i_gcd = gcd(self._interval, base)
|
1070 |
+
# Use divmod rather than % because we need to wrap negative nums.
|
1071 |
+
if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0:
|
1072 |
+
cset.add(num)
|
1073 |
+
|
1074 |
+
if len(cset) == 0:
|
1075 |
+
raise ValueError("Invalid rrule byxxx generates an empty set.")
|
1076 |
+
|
1077 |
+
return cset
|
1078 |
+
|
1079 |
+
def __mod_distance(self, value, byxxx, base):
|
1080 |
+
"""
|
1081 |
+
Calculates the next value in a sequence where the `FREQ` parameter is
|
1082 |
+
specified along with a `BYXXX` parameter at the same "level"
|
1083 |
+
(e.g. `HOURLY` specified with `BYHOUR`).
|
1084 |
+
|
1085 |
+
:param value:
|
1086 |
+
The old value of the component.
|
1087 |
+
:param byxxx:
|
1088 |
+
The `BYXXX` set, which should have been generated by
|
1089 |
+
`rrule._construct_byset`, or something else which checks that a
|
1090 |
+
valid rule is present.
|
1091 |
+
:param base:
|
1092 |
+
The largest allowable value for the specified frequency (e.g.
|
1093 |
+
24 hours, 60 minutes).
|
1094 |
+
|
1095 |
+
If a valid value is not found after `base` iterations (the maximum
|
1096 |
+
number before the sequence would start to repeat), this raises a
|
1097 |
+
:exception:`ValueError`, as no valid values were found.
|
1098 |
+
|
1099 |
+
This returns a tuple of `divmod(n*interval, base)`, where `n` is the
|
1100 |
+
smallest number of `interval` repetitions until the next specified
|
1101 |
+
value in `byxxx` is found.
|
1102 |
+
"""
|
1103 |
+
accumulator = 0
|
1104 |
+
for ii in range(1, base + 1):
|
1105 |
+
# Using divmod() over % to account for negative intervals
|
1106 |
+
div, value = divmod(value + self._interval, base)
|
1107 |
+
accumulator += div
|
1108 |
+
if value in byxxx:
|
1109 |
+
return (accumulator, value)
|
1110 |
+
|
1111 |
+
|
1112 |
+
class _iterinfo(object):
|
1113 |
+
__slots__ = ["rrule", "lastyear", "lastmonth",
|
1114 |
+
"yearlen", "nextyearlen", "yearordinal", "yearweekday",
|
1115 |
+
"mmask", "mrange", "mdaymask", "nmdaymask",
|
1116 |
+
"wdaymask", "wnomask", "nwdaymask", "eastermask"]
|
1117 |
+
|
1118 |
+
def __init__(self, rrule):
|
1119 |
+
for attr in self.__slots__:
|
1120 |
+
setattr(self, attr, None)
|
1121 |
+
self.rrule = rrule
|
1122 |
+
|
1123 |
+
def rebuild(self, year, month):
|
1124 |
+
# Every mask is 7 days longer to handle cross-year weekly periods.
|
1125 |
+
rr = self.rrule
|
1126 |
+
if year != self.lastyear:
|
1127 |
+
self.yearlen = 365 + calendar.isleap(year)
|
1128 |
+
self.nextyearlen = 365 + calendar.isleap(year + 1)
|
1129 |
+
firstyday = datetime.date(year, 1, 1)
|
1130 |
+
self.yearordinal = firstyday.toordinal()
|
1131 |
+
self.yearweekday = firstyday.weekday()
|
1132 |
+
|
1133 |
+
wday = datetime.date(year, 1, 1).weekday()
|
1134 |
+
if self.yearlen == 365:
|
1135 |
+
self.mmask = M365MASK
|
1136 |
+
self.mdaymask = MDAY365MASK
|
1137 |
+
self.nmdaymask = NMDAY365MASK
|
1138 |
+
self.wdaymask = WDAYMASK[wday:]
|
1139 |
+
self.mrange = M365RANGE
|
1140 |
+
else:
|
1141 |
+
self.mmask = M366MASK
|
1142 |
+
self.mdaymask = MDAY366MASK
|
1143 |
+
self.nmdaymask = NMDAY366MASK
|
1144 |
+
self.wdaymask = WDAYMASK[wday:]
|
1145 |
+
self.mrange = M366RANGE
|
1146 |
+
|
1147 |
+
if not rr._byweekno:
|
1148 |
+
self.wnomask = None
|
1149 |
+
else:
|
1150 |
+
self.wnomask = [0]*(self.yearlen+7)
|
1151 |
+
# no1wkst = firstwkst = self.wdaymask.index(rr._wkst)
|
1152 |
+
no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7
|
1153 |
+
if no1wkst >= 4:
|
1154 |
+
no1wkst = 0
|
1155 |
+
# Number of days in the year, plus the days we got
|
1156 |
+
# from last year.
|
1157 |
+
wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7
|
1158 |
+
else:
|
1159 |
+
# Number of days in the year, minus the days we
|
1160 |
+
# left in last year.
|
1161 |
+
wyearlen = self.yearlen-no1wkst
|
1162 |
+
div, mod = divmod(wyearlen, 7)
|
1163 |
+
numweeks = div+mod//4
|
1164 |
+
for n in rr._byweekno:
|
1165 |
+
if n < 0:
|
1166 |
+
n += numweeks+1
|
1167 |
+
if not (0 < n <= numweeks):
|
1168 |
+
continue
|
1169 |
+
if n > 1:
|
1170 |
+
i = no1wkst+(n-1)*7
|
1171 |
+
if no1wkst != firstwkst:
|
1172 |
+
i -= 7-firstwkst
|
1173 |
+
else:
|
1174 |
+
i = no1wkst
|
1175 |
+
for j in range(7):
|
1176 |
+
self.wnomask[i] = 1
|
1177 |
+
i += 1
|
1178 |
+
if self.wdaymask[i] == rr._wkst:
|
1179 |
+
break
|
1180 |
+
if 1 in rr._byweekno:
|
1181 |
+
# Check week number 1 of next year as well
|
1182 |
+
# TODO: Check -numweeks for next year.
|
1183 |
+
i = no1wkst+numweeks*7
|
1184 |
+
if no1wkst != firstwkst:
|
1185 |
+
i -= 7-firstwkst
|
1186 |
+
if i < self.yearlen:
|
1187 |
+
# If week starts in next year, we
|
1188 |
+
# don't care about it.
|
1189 |
+
for j in range(7):
|
1190 |
+
self.wnomask[i] = 1
|
1191 |
+
i += 1
|
1192 |
+
if self.wdaymask[i] == rr._wkst:
|
1193 |
+
break
|
1194 |
+
if no1wkst:
|
1195 |
+
# Check last week number of last year as
|
1196 |
+
# well. If no1wkst is 0, either the year
|
1197 |
+
# started on week start, or week number 1
|
1198 |
+
# got days from last year, so there are no
|
1199 |
+
# days from last year's last week number in
|
1200 |
+
# this year.
|
1201 |
+
if -1 not in rr._byweekno:
|
1202 |
+
lyearweekday = datetime.date(year-1, 1, 1).weekday()
|
1203 |
+
lno1wkst = (7-lyearweekday+rr._wkst) % 7
|
1204 |
+
lyearlen = 365+calendar.isleap(year-1)
|
1205 |
+
if lno1wkst >= 4:
|
1206 |
+
lno1wkst = 0
|
1207 |
+
lnumweeks = 52+(lyearlen +
|
1208 |
+
(lyearweekday-rr._wkst) % 7) % 7//4
|
1209 |
+
else:
|
1210 |
+
lnumweeks = 52+(self.yearlen-no1wkst) % 7//4
|
1211 |
+
else:
|
1212 |
+
lnumweeks = -1
|
1213 |
+
if lnumweeks in rr._byweekno:
|
1214 |
+
for i in range(no1wkst):
|
1215 |
+
self.wnomask[i] = 1
|
1216 |
+
|
1217 |
+
if (rr._bynweekday and (month != self.lastmonth or
|
1218 |
+
year != self.lastyear)):
|
1219 |
+
ranges = []
|
1220 |
+
if rr._freq == YEARLY:
|
1221 |
+
if rr._bymonth:
|
1222 |
+
for month in rr._bymonth:
|
1223 |
+
ranges.append(self.mrange[month-1:month+1])
|
1224 |
+
else:
|
1225 |
+
ranges = [(0, self.yearlen)]
|
1226 |
+
elif rr._freq == MONTHLY:
|
1227 |
+
ranges = [self.mrange[month-1:month+1]]
|
1228 |
+
if ranges:
|
1229 |
+
# Weekly frequency won't get here, so we may not
|
1230 |
+
# care about cross-year weekly periods.
|
1231 |
+
self.nwdaymask = [0]*self.yearlen
|
1232 |
+
for first, last in ranges:
|
1233 |
+
last -= 1
|
1234 |
+
for wday, n in rr._bynweekday:
|
1235 |
+
if n < 0:
|
1236 |
+
i = last+(n+1)*7
|
1237 |
+
i -= (self.wdaymask[i]-wday) % 7
|
1238 |
+
else:
|
1239 |
+
i = first+(n-1)*7
|
1240 |
+
i += (7-self.wdaymask[i]+wday) % 7
|
1241 |
+
if first <= i <= last:
|
1242 |
+
self.nwdaymask[i] = 1
|
1243 |
+
|
1244 |
+
if rr._byeaster:
|
1245 |
+
self.eastermask = [0]*(self.yearlen+7)
|
1246 |
+
eyday = easter.easter(year).toordinal()-self.yearordinal
|
1247 |
+
for offset in rr._byeaster:
|
1248 |
+
self.eastermask[eyday+offset] = 1
|
1249 |
+
|
1250 |
+
self.lastyear = year
|
1251 |
+
self.lastmonth = month
|
1252 |
+
|
1253 |
+
def ydayset(self, year, month, day):
|
1254 |
+
return list(range(self.yearlen)), 0, self.yearlen
|
1255 |
+
|
1256 |
+
def mdayset(self, year, month, day):
|
1257 |
+
dset = [None]*self.yearlen
|
1258 |
+
start, end = self.mrange[month-1:month+1]
|
1259 |
+
for i in range(start, end):
|
1260 |
+
dset[i] = i
|
1261 |
+
return dset, start, end
|
1262 |
+
|
1263 |
+
def wdayset(self, year, month, day):
|
1264 |
+
# We need to handle cross-year weeks here.
|
1265 |
+
dset = [None]*(self.yearlen+7)
|
1266 |
+
i = datetime.date(year, month, day).toordinal()-self.yearordinal
|
1267 |
+
start = i
|
1268 |
+
for j in range(7):
|
1269 |
+
dset[i] = i
|
1270 |
+
i += 1
|
1271 |
+
# if (not (0 <= i < self.yearlen) or
|
1272 |
+
# self.wdaymask[i] == self.rrule._wkst):
|
1273 |
+
# This will cross the year boundary, if necessary.
|
1274 |
+
if self.wdaymask[i] == self.rrule._wkst:
|
1275 |
+
break
|
1276 |
+
return dset, start, i
|
1277 |
+
|
1278 |
+
def ddayset(self, year, month, day):
|
1279 |
+
dset = [None] * self.yearlen
|
1280 |
+
i = datetime.date(year, month, day).toordinal() - self.yearordinal
|
1281 |
+
dset[i] = i
|
1282 |
+
return dset, i, i + 1
|
1283 |
+
|
1284 |
+
def htimeset(self, hour, minute, second):
|
1285 |
+
tset = []
|
1286 |
+
rr = self.rrule
|
1287 |
+
for minute in rr._byminute:
|
1288 |
+
for second in rr._bysecond:
|
1289 |
+
tset.append(datetime.time(hour, minute, second,
|
1290 |
+
tzinfo=rr._tzinfo))
|
1291 |
+
tset.sort()
|
1292 |
+
return tset
|
1293 |
+
|
1294 |
+
def mtimeset(self, hour, minute, second):
|
1295 |
+
tset = []
|
1296 |
+
rr = self.rrule
|
1297 |
+
for second in rr._bysecond:
|
1298 |
+
tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo))
|
1299 |
+
tset.sort()
|
1300 |
+
return tset
|
1301 |
+
|
1302 |
+
def stimeset(self, hour, minute, second):
|
1303 |
+
return (datetime.time(hour, minute, second,
|
1304 |
+
tzinfo=self.rrule._tzinfo),)
|
1305 |
+
|
1306 |
+
|
1307 |
+
class rruleset(rrulebase):
|
1308 |
+
""" The rruleset type allows more complex recurrence setups, mixing
|
1309 |
+
multiple rules, dates, exclusion rules, and exclusion dates. The type
|
1310 |
+
constructor takes the following keyword arguments:
|
1311 |
+
|
1312 |
+
:param cache: If True, caching of results will be enabled, improving
|
1313 |
+
performance of multiple queries considerably. """
|
1314 |
+
|
1315 |
+
class _genitem(object):
|
1316 |
+
def __init__(self, genlist, gen):
|
1317 |
+
try:
|
1318 |
+
self.dt = advance_iterator(gen)
|
1319 |
+
genlist.append(self)
|
1320 |
+
except StopIteration:
|
1321 |
+
pass
|
1322 |
+
self.genlist = genlist
|
1323 |
+
self.gen = gen
|
1324 |
+
|
1325 |
+
def __next__(self):
|
1326 |
+
try:
|
1327 |
+
self.dt = advance_iterator(self.gen)
|
1328 |
+
except StopIteration:
|
1329 |
+
if self.genlist[0] is self:
|
1330 |
+
heapq.heappop(self.genlist)
|
1331 |
+
else:
|
1332 |
+
self.genlist.remove(self)
|
1333 |
+
heapq.heapify(self.genlist)
|
1334 |
+
|
1335 |
+
next = __next__
|
1336 |
+
|
1337 |
+
def __lt__(self, other):
|
1338 |
+
return self.dt < other.dt
|
1339 |
+
|
1340 |
+
def __gt__(self, other):
|
1341 |
+
return self.dt > other.dt
|
1342 |
+
|
1343 |
+
def __eq__(self, other):
|
1344 |
+
return self.dt == other.dt
|
1345 |
+
|
1346 |
+
def __ne__(self, other):
|
1347 |
+
return self.dt != other.dt
|
1348 |
+
|
1349 |
+
def __init__(self, cache=False):
|
1350 |
+
super(rruleset, self).__init__(cache)
|
1351 |
+
self._rrule = []
|
1352 |
+
self._rdate = []
|
1353 |
+
self._exrule = []
|
1354 |
+
self._exdate = []
|
1355 |
+
|
1356 |
+
@_invalidates_cache
|
1357 |
+
def rrule(self, rrule):
|
1358 |
+
""" Include the given :py:class:`rrule` instance in the recurrence set
|
1359 |
+
generation. """
|
1360 |
+
self._rrule.append(rrule)
|
1361 |
+
|
1362 |
+
@_invalidates_cache
|
1363 |
+
def rdate(self, rdate):
|
1364 |
+
""" Include the given :py:class:`datetime` instance in the recurrence
|
1365 |
+
set generation. """
|
1366 |
+
self._rdate.append(rdate)
|
1367 |
+
|
1368 |
+
@_invalidates_cache
|
1369 |
+
def exrule(self, exrule):
|
1370 |
+
""" Include the given rrule instance in the recurrence set exclusion
|
1371 |
+
list. Dates which are part of the given recurrence rules will not
|
1372 |
+
be generated, even if some inclusive rrule or rdate matches them.
|
1373 |
+
"""
|
1374 |
+
self._exrule.append(exrule)
|
1375 |
+
|
1376 |
+
@_invalidates_cache
|
1377 |
+
def exdate(self, exdate):
|
1378 |
+
""" Include the given datetime instance in the recurrence set
|
1379 |
+
exclusion list. Dates included that way will not be generated,
|
1380 |
+
even if some inclusive rrule or rdate matches them. """
|
1381 |
+
self._exdate.append(exdate)
|
1382 |
+
|
1383 |
+
def _iter(self):
|
1384 |
+
rlist = []
|
1385 |
+
self._rdate.sort()
|
1386 |
+
self._genitem(rlist, iter(self._rdate))
|
1387 |
+
for gen in [iter(x) for x in self._rrule]:
|
1388 |
+
self._genitem(rlist, gen)
|
1389 |
+
exlist = []
|
1390 |
+
self._exdate.sort()
|
1391 |
+
self._genitem(exlist, iter(self._exdate))
|
1392 |
+
for gen in [iter(x) for x in self._exrule]:
|
1393 |
+
self._genitem(exlist, gen)
|
1394 |
+
lastdt = None
|
1395 |
+
total = 0
|
1396 |
+
heapq.heapify(rlist)
|
1397 |
+
heapq.heapify(exlist)
|
1398 |
+
while rlist:
|
1399 |
+
ritem = rlist[0]
|
1400 |
+
if not lastdt or lastdt != ritem.dt:
|
1401 |
+
while exlist and exlist[0] < ritem:
|
1402 |
+
exitem = exlist[0]
|
1403 |
+
advance_iterator(exitem)
|
1404 |
+
if exlist and exlist[0] is exitem:
|
1405 |
+
heapq.heapreplace(exlist, exitem)
|
1406 |
+
if not exlist or ritem != exlist[0]:
|
1407 |
+
total += 1
|
1408 |
+
yield ritem.dt
|
1409 |
+
lastdt = ritem.dt
|
1410 |
+
advance_iterator(ritem)
|
1411 |
+
if rlist and rlist[0] is ritem:
|
1412 |
+
heapq.heapreplace(rlist, ritem)
|
1413 |
+
self._len = total
|
1414 |
+
|
1415 |
+
|
1416 |
+
|
1417 |
+
|
1418 |
+
class _rrulestr(object):
|
1419 |
+
""" Parses a string representation of a recurrence rule or set of
|
1420 |
+
recurrence rules.
|
1421 |
+
|
1422 |
+
:param s:
|
1423 |
+
Required, a string defining one or more recurrence rules.
|
1424 |
+
|
1425 |
+
:param dtstart:
|
1426 |
+
If given, used as the default recurrence start if not specified in the
|
1427 |
+
rule string.
|
1428 |
+
|
1429 |
+
:param cache:
|
1430 |
+
If set ``True`` caching of results will be enabled, improving
|
1431 |
+
performance of multiple queries considerably.
|
1432 |
+
|
1433 |
+
:param unfold:
|
1434 |
+
If set ``True`` indicates that a rule string is split over more
|
1435 |
+
than one line and should be joined before processing.
|
1436 |
+
|
1437 |
+
:param forceset:
|
1438 |
+
If set ``True`` forces a :class:`dateutil.rrule.rruleset` to
|
1439 |
+
be returned.
|
1440 |
+
|
1441 |
+
:param compatible:
|
1442 |
+
If set ``True`` forces ``unfold`` and ``forceset`` to be ``True``.
|
1443 |
+
|
1444 |
+
:param ignoretz:
|
1445 |
+
If set ``True``, time zones in parsed strings are ignored and a naive
|
1446 |
+
:class:`datetime.datetime` object is returned.
|
1447 |
+
|
1448 |
+
:param tzids:
|
1449 |
+
If given, a callable or mapping used to retrieve a
|
1450 |
+
:class:`datetime.tzinfo` from a string representation.
|
1451 |
+
Defaults to :func:`dateutil.tz.gettz`.
|
1452 |
+
|
1453 |
+
:param tzinfos:
|
1454 |
+
Additional time zone names / aliases which may be present in a string
|
1455 |
+
representation. See :func:`dateutil.parser.parse` for more
|
1456 |
+
information.
|
1457 |
+
|
1458 |
+
:return:
|
1459 |
+
Returns a :class:`dateutil.rrule.rruleset` or
|
1460 |
+
:class:`dateutil.rrule.rrule`
|
1461 |
+
"""
|
1462 |
+
|
1463 |
+
_freq_map = {"YEARLY": YEARLY,
|
1464 |
+
"MONTHLY": MONTHLY,
|
1465 |
+
"WEEKLY": WEEKLY,
|
1466 |
+
"DAILY": DAILY,
|
1467 |
+
"HOURLY": HOURLY,
|
1468 |
+
"MINUTELY": MINUTELY,
|
1469 |
+
"SECONDLY": SECONDLY}
|
1470 |
+
|
1471 |
+
_weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3,
|
1472 |
+
"FR": 4, "SA": 5, "SU": 6}
|
1473 |
+
|
1474 |
+
def _handle_int(self, rrkwargs, name, value, **kwargs):
|
1475 |
+
rrkwargs[name.lower()] = int(value)
|
1476 |
+
|
1477 |
+
def _handle_int_list(self, rrkwargs, name, value, **kwargs):
|
1478 |
+
rrkwargs[name.lower()] = [int(x) for x in value.split(',')]
|
1479 |
+
|
1480 |
+
_handle_INTERVAL = _handle_int
|
1481 |
+
_handle_COUNT = _handle_int
|
1482 |
+
_handle_BYSETPOS = _handle_int_list
|
1483 |
+
_handle_BYMONTH = _handle_int_list
|
1484 |
+
_handle_BYMONTHDAY = _handle_int_list
|
1485 |
+
_handle_BYYEARDAY = _handle_int_list
|
1486 |
+
_handle_BYEASTER = _handle_int_list
|
1487 |
+
_handle_BYWEEKNO = _handle_int_list
|
1488 |
+
_handle_BYHOUR = _handle_int_list
|
1489 |
+
_handle_BYMINUTE = _handle_int_list
|
1490 |
+
_handle_BYSECOND = _handle_int_list
|
1491 |
+
|
1492 |
+
def _handle_FREQ(self, rrkwargs, name, value, **kwargs):
|
1493 |
+
rrkwargs["freq"] = self._freq_map[value]
|
1494 |
+
|
1495 |
+
def _handle_UNTIL(self, rrkwargs, name, value, **kwargs):
|
1496 |
+
global parser
|
1497 |
+
if not parser:
|
1498 |
+
from dateutil import parser
|
1499 |
+
try:
|
1500 |
+
rrkwargs["until"] = parser.parse(value,
|
1501 |
+
ignoretz=kwargs.get("ignoretz"),
|
1502 |
+
tzinfos=kwargs.get("tzinfos"))
|
1503 |
+
except ValueError:
|
1504 |
+
raise ValueError("invalid until date")
|
1505 |
+
|
1506 |
+
def _handle_WKST(self, rrkwargs, name, value, **kwargs):
|
1507 |
+
rrkwargs["wkst"] = self._weekday_map[value]
|
1508 |
+
|
1509 |
+
def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs):
|
1510 |
+
"""
|
1511 |
+
Two ways to specify this: +1MO or MO(+1)
|
1512 |
+
"""
|
1513 |
+
l = []
|
1514 |
+
for wday in value.split(','):
|
1515 |
+
if '(' in wday:
|
1516 |
+
# If it's of the form TH(+1), etc.
|
1517 |
+
splt = wday.split('(')
|
1518 |
+
w = splt[0]
|
1519 |
+
n = int(splt[1][:-1])
|
1520 |
+
elif len(wday):
|
1521 |
+
# If it's of the form +1MO
|
1522 |
+
for i in range(len(wday)):
|
1523 |
+
if wday[i] not in '+-0123456789':
|
1524 |
+
break
|
1525 |
+
n = wday[:i] or None
|
1526 |
+
w = wday[i:]
|
1527 |
+
if n:
|
1528 |
+
n = int(n)
|
1529 |
+
else:
|
1530 |
+
raise ValueError("Invalid (empty) BYDAY specification.")
|
1531 |
+
|
1532 |
+
l.append(weekdays[self._weekday_map[w]](n))
|
1533 |
+
rrkwargs["byweekday"] = l
|
1534 |
+
|
1535 |
+
_handle_BYDAY = _handle_BYWEEKDAY
|
1536 |
+
|
1537 |
+
def _parse_rfc_rrule(self, line,
|
1538 |
+
dtstart=None,
|
1539 |
+
cache=False,
|
1540 |
+
ignoretz=False,
|
1541 |
+
tzinfos=None):
|
1542 |
+
if line.find(':') != -1:
|
1543 |
+
name, value = line.split(':')
|
1544 |
+
if name != "RRULE":
|
1545 |
+
raise ValueError("unknown parameter name")
|
1546 |
+
else:
|
1547 |
+
value = line
|
1548 |
+
rrkwargs = {}
|
1549 |
+
for pair in value.split(';'):
|
1550 |
+
name, value = pair.split('=')
|
1551 |
+
name = name.upper()
|
1552 |
+
value = value.upper()
|
1553 |
+
try:
|
1554 |
+
getattr(self, "_handle_"+name)(rrkwargs, name, value,
|
1555 |
+
ignoretz=ignoretz,
|
1556 |
+
tzinfos=tzinfos)
|
1557 |
+
except AttributeError:
|
1558 |
+
raise ValueError("unknown parameter '%s'" % name)
|
1559 |
+
except (KeyError, ValueError):
|
1560 |
+
raise ValueError("invalid '%s': %s" % (name, value))
|
1561 |
+
return rrule(dtstart=dtstart, cache=cache, **rrkwargs)
|
1562 |
+
|
1563 |
+
def _parse_date_value(self, date_value, parms, rule_tzids,
|
1564 |
+
ignoretz, tzids, tzinfos):
|
1565 |
+
global parser
|
1566 |
+
if not parser:
|
1567 |
+
from dateutil import parser
|
1568 |
+
|
1569 |
+
datevals = []
|
1570 |
+
value_found = False
|
1571 |
+
TZID = None
|
1572 |
+
|
1573 |
+
for parm in parms:
|
1574 |
+
if parm.startswith("TZID="):
|
1575 |
+
try:
|
1576 |
+
tzkey = rule_tzids[parm.split('TZID=')[-1]]
|
1577 |
+
except KeyError:
|
1578 |
+
continue
|
1579 |
+
if tzids is None:
|
1580 |
+
from . import tz
|
1581 |
+
tzlookup = tz.gettz
|
1582 |
+
elif callable(tzids):
|
1583 |
+
tzlookup = tzids
|
1584 |
+
else:
|
1585 |
+
tzlookup = getattr(tzids, 'get', None)
|
1586 |
+
if tzlookup is None:
|
1587 |
+
msg = ('tzids must be a callable, mapping, or None, '
|
1588 |
+
'not %s' % tzids)
|
1589 |
+
raise ValueError(msg)
|
1590 |
+
|
1591 |
+
TZID = tzlookup(tzkey)
|
1592 |
+
continue
|
1593 |
+
|
1594 |
+
# RFC 5445 3.8.2.4: The VALUE parameter is optional, but may be found
|
1595 |
+
# only once.
|
1596 |
+
if parm not in {"VALUE=DATE-TIME", "VALUE=DATE"}:
|
1597 |
+
raise ValueError("unsupported parm: " + parm)
|
1598 |
+
else:
|
1599 |
+
if value_found:
|
1600 |
+
msg = ("Duplicate value parameter found in: " + parm)
|
1601 |
+
raise ValueError(msg)
|
1602 |
+
value_found = True
|
1603 |
+
|
1604 |
+
for datestr in date_value.split(','):
|
1605 |
+
date = parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos)
|
1606 |
+
if TZID is not None:
|
1607 |
+
if date.tzinfo is None:
|
1608 |
+
date = date.replace(tzinfo=TZID)
|
1609 |
+
else:
|
1610 |
+
raise ValueError('DTSTART/EXDATE specifies multiple timezone')
|
1611 |
+
datevals.append(date)
|
1612 |
+
|
1613 |
+
return datevals
|
1614 |
+
|
1615 |
+
def _parse_rfc(self, s,
|
1616 |
+
dtstart=None,
|
1617 |
+
cache=False,
|
1618 |
+
unfold=False,
|
1619 |
+
forceset=False,
|
1620 |
+
compatible=False,
|
1621 |
+
ignoretz=False,
|
1622 |
+
tzids=None,
|
1623 |
+
tzinfos=None):
|
1624 |
+
global parser
|
1625 |
+
if compatible:
|
1626 |
+
forceset = True
|
1627 |
+
unfold = True
|
1628 |
+
|
1629 |
+
TZID_NAMES = dict(map(
|
1630 |
+
lambda x: (x.upper(), x),
|
1631 |
+
re.findall('TZID=(?P<name>[^:]+):', s)
|
1632 |
+
))
|
1633 |
+
s = s.upper()
|
1634 |
+
if not s.strip():
|
1635 |
+
raise ValueError("empty string")
|
1636 |
+
if unfold:
|
1637 |
+
lines = s.splitlines()
|
1638 |
+
i = 0
|
1639 |
+
while i < len(lines):
|
1640 |
+
line = lines[i].rstrip()
|
1641 |
+
if not line:
|
1642 |
+
del lines[i]
|
1643 |
+
elif i > 0 and line[0] == " ":
|
1644 |
+
lines[i-1] += line[1:]
|
1645 |
+
del lines[i]
|
1646 |
+
else:
|
1647 |
+
i += 1
|
1648 |
+
else:
|
1649 |
+
lines = s.split()
|
1650 |
+
if (not forceset and len(lines) == 1 and (s.find(':') == -1 or
|
1651 |
+
s.startswith('RRULE:'))):
|
1652 |
+
return self._parse_rfc_rrule(lines[0], cache=cache,
|
1653 |
+
dtstart=dtstart, ignoretz=ignoretz,
|
1654 |
+
tzinfos=tzinfos)
|
1655 |
+
else:
|
1656 |
+
rrulevals = []
|
1657 |
+
rdatevals = []
|
1658 |
+
exrulevals = []
|
1659 |
+
exdatevals = []
|
1660 |
+
for line in lines:
|
1661 |
+
if not line:
|
1662 |
+
continue
|
1663 |
+
if line.find(':') == -1:
|
1664 |
+
name = "RRULE"
|
1665 |
+
value = line
|
1666 |
+
else:
|
1667 |
+
name, value = line.split(':', 1)
|
1668 |
+
parms = name.split(';')
|
1669 |
+
if not parms:
|
1670 |
+
raise ValueError("empty property name")
|
1671 |
+
name = parms[0]
|
1672 |
+
parms = parms[1:]
|
1673 |
+
if name == "RRULE":
|
1674 |
+
for parm in parms:
|
1675 |
+
raise ValueError("unsupported RRULE parm: "+parm)
|
1676 |
+
rrulevals.append(value)
|
1677 |
+
elif name == "RDATE":
|
1678 |
+
for parm in parms:
|
1679 |
+
if parm != "VALUE=DATE-TIME":
|
1680 |
+
raise ValueError("unsupported RDATE parm: "+parm)
|
1681 |
+
rdatevals.append(value)
|
1682 |
+
elif name == "EXRULE":
|
1683 |
+
for parm in parms:
|
1684 |
+
raise ValueError("unsupported EXRULE parm: "+parm)
|
1685 |
+
exrulevals.append(value)
|
1686 |
+
elif name == "EXDATE":
|
1687 |
+
exdatevals.extend(
|
1688 |
+
self._parse_date_value(value, parms,
|
1689 |
+
TZID_NAMES, ignoretz,
|
1690 |
+
tzids, tzinfos)
|
1691 |
+
)
|
1692 |
+
elif name == "DTSTART":
|
1693 |
+
dtvals = self._parse_date_value(value, parms, TZID_NAMES,
|
1694 |
+
ignoretz, tzids, tzinfos)
|
1695 |
+
if len(dtvals) != 1:
|
1696 |
+
raise ValueError("Multiple DTSTART values specified:" +
|
1697 |
+
value)
|
1698 |
+
dtstart = dtvals[0]
|
1699 |
+
else:
|
1700 |
+
raise ValueError("unsupported property: "+name)
|
1701 |
+
if (forceset or len(rrulevals) > 1 or rdatevals
|
1702 |
+
or exrulevals or exdatevals):
|
1703 |
+
if not parser and (rdatevals or exdatevals):
|
1704 |
+
from dateutil import parser
|
1705 |
+
rset = rruleset(cache=cache)
|
1706 |
+
for value in rrulevals:
|
1707 |
+
rset.rrule(self._parse_rfc_rrule(value, dtstart=dtstart,
|
1708 |
+
ignoretz=ignoretz,
|
1709 |
+
tzinfos=tzinfos))
|
1710 |
+
for value in rdatevals:
|
1711 |
+
for datestr in value.split(','):
|
1712 |
+
rset.rdate(parser.parse(datestr,
|
1713 |
+
ignoretz=ignoretz,
|
1714 |
+
tzinfos=tzinfos))
|
1715 |
+
for value in exrulevals:
|
1716 |
+
rset.exrule(self._parse_rfc_rrule(value, dtstart=dtstart,
|
1717 |
+
ignoretz=ignoretz,
|
1718 |
+
tzinfos=tzinfos))
|
1719 |
+
for value in exdatevals:
|
1720 |
+
rset.exdate(value)
|
1721 |
+
if compatible and dtstart:
|
1722 |
+
rset.rdate(dtstart)
|
1723 |
+
return rset
|
1724 |
+
else:
|
1725 |
+
return self._parse_rfc_rrule(rrulevals[0],
|
1726 |
+
dtstart=dtstart,
|
1727 |
+
cache=cache,
|
1728 |
+
ignoretz=ignoretz,
|
1729 |
+
tzinfos=tzinfos)
|
1730 |
+
|
1731 |
+
def __call__(self, s, **kwargs):
|
1732 |
+
return self._parse_rfc(s, **kwargs)
|
1733 |
+
|
1734 |
+
|
1735 |
+
rrulestr = _rrulestr()
|
1736 |
+
|
1737 |
+
# vim:ts=4:sw=4:et
|
venv/lib/python3.10/site-packages/dateutil/tz/__init__.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
from .tz import *
|
3 |
+
from .tz import __doc__
|
4 |
+
|
5 |
+
__all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange",
|
6 |
+
"tzstr", "tzical", "tzwin", "tzwinlocal", "gettz",
|
7 |
+
"enfold", "datetime_ambiguous", "datetime_exists",
|
8 |
+
"resolve_imaginary", "UTC", "DeprecatedTzFormatWarning"]
|
9 |
+
|
10 |
+
|
11 |
+
class DeprecatedTzFormatWarning(Warning):
|
12 |
+
"""Warning raised when time zones are parsed from deprecated formats."""
|
venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (669 Bytes). View file
|
|
venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/_common.cpython-310.pyc
ADDED
Binary file (10.8 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/_factories.cpython-310.pyc
ADDED
Binary file (2.94 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/tz.cpython-310.pyc
ADDED
Binary file (44.9 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/tz/__pycache__/win.cpython-310.pyc
ADDED
Binary file (11.4 kB). View file
|
|
venv/lib/python3.10/site-packages/dateutil/tz/_common.py
ADDED
@@ -0,0 +1,419 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from six import PY2
|
2 |
+
|
3 |
+
from functools import wraps
|
4 |
+
|
5 |
+
from datetime import datetime, timedelta, tzinfo
|
6 |
+
|
7 |
+
|
8 |
+
ZERO = timedelta(0)
|
9 |
+
|
10 |
+
__all__ = ['tzname_in_python2', 'enfold']
|
11 |
+
|
12 |
+
|
13 |
+
def tzname_in_python2(namefunc):
|
14 |
+
"""Change unicode output into bytestrings in Python 2
|
15 |
+
|
16 |
+
tzname() API changed in Python 3. It used to return bytes, but was changed
|
17 |
+
to unicode strings
|
18 |
+
"""
|
19 |
+
if PY2:
|
20 |
+
@wraps(namefunc)
|
21 |
+
def adjust_encoding(*args, **kwargs):
|
22 |
+
name = namefunc(*args, **kwargs)
|
23 |
+
if name is not None:
|
24 |
+
name = name.encode()
|
25 |
+
|
26 |
+
return name
|
27 |
+
|
28 |
+
return adjust_encoding
|
29 |
+
else:
|
30 |
+
return namefunc
|
31 |
+
|
32 |
+
|
33 |
+
# The following is adapted from Alexander Belopolsky's tz library
|
34 |
+
# https://github.com/abalkin/tz
|
35 |
+
if hasattr(datetime, 'fold'):
|
36 |
+
# This is the pre-python 3.6 fold situation
|
37 |
+
def enfold(dt, fold=1):
|
38 |
+
"""
|
39 |
+
Provides a unified interface for assigning the ``fold`` attribute to
|
40 |
+
datetimes both before and after the implementation of PEP-495.
|
41 |
+
|
42 |
+
:param fold:
|
43 |
+
The value for the ``fold`` attribute in the returned datetime. This
|
44 |
+
should be either 0 or 1.
|
45 |
+
|
46 |
+
:return:
|
47 |
+
Returns an object for which ``getattr(dt, 'fold', 0)`` returns
|
48 |
+
``fold`` for all versions of Python. In versions prior to
|
49 |
+
Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
|
50 |
+
subclass of :py:class:`datetime.datetime` with the ``fold``
|
51 |
+
attribute added, if ``fold`` is 1.
|
52 |
+
|
53 |
+
.. versionadded:: 2.6.0
|
54 |
+
"""
|
55 |
+
return dt.replace(fold=fold)
|
56 |
+
|
57 |
+
else:
|
58 |
+
class _DatetimeWithFold(datetime):
|
59 |
+
"""
|
60 |
+
This is a class designed to provide a PEP 495-compliant interface for
|
61 |
+
Python versions before 3.6. It is used only for dates in a fold, so
|
62 |
+
the ``fold`` attribute is fixed at ``1``.
|
63 |
+
|
64 |
+
.. versionadded:: 2.6.0
|
65 |
+
"""
|
66 |
+
__slots__ = ()
|
67 |
+
|
68 |
+
def replace(self, *args, **kwargs):
|
69 |
+
"""
|
70 |
+
Return a datetime with the same attributes, except for those
|
71 |
+
attributes given new values by whichever keyword arguments are
|
72 |
+
specified. Note that tzinfo=None can be specified to create a naive
|
73 |
+
datetime from an aware datetime with no conversion of date and time
|
74 |
+
data.
|
75 |
+
|
76 |
+
This is reimplemented in ``_DatetimeWithFold`` because pypy3 will
|
77 |
+
return a ``datetime.datetime`` even if ``fold`` is unchanged.
|
78 |
+
"""
|
79 |
+
argnames = (
|
80 |
+
'year', 'month', 'day', 'hour', 'minute', 'second',
|
81 |
+
'microsecond', 'tzinfo'
|
82 |
+
)
|
83 |
+
|
84 |
+
for arg, argname in zip(args, argnames):
|
85 |
+
if argname in kwargs:
|
86 |
+
raise TypeError('Duplicate argument: {}'.format(argname))
|
87 |
+
|
88 |
+
kwargs[argname] = arg
|
89 |
+
|
90 |
+
for argname in argnames:
|
91 |
+
if argname not in kwargs:
|
92 |
+
kwargs[argname] = getattr(self, argname)
|
93 |
+
|
94 |
+
dt_class = self.__class__ if kwargs.get('fold', 1) else datetime
|
95 |
+
|
96 |
+
return dt_class(**kwargs)
|
97 |
+
|
98 |
+
@property
|
99 |
+
def fold(self):
|
100 |
+
return 1
|
101 |
+
|
102 |
+
def enfold(dt, fold=1):
|
103 |
+
"""
|
104 |
+
Provides a unified interface for assigning the ``fold`` attribute to
|
105 |
+
datetimes both before and after the implementation of PEP-495.
|
106 |
+
|
107 |
+
:param fold:
|
108 |
+
The value for the ``fold`` attribute in the returned datetime. This
|
109 |
+
should be either 0 or 1.
|
110 |
+
|
111 |
+
:return:
|
112 |
+
Returns an object for which ``getattr(dt, 'fold', 0)`` returns
|
113 |
+
``fold`` for all versions of Python. In versions prior to
|
114 |
+
Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
|
115 |
+
subclass of :py:class:`datetime.datetime` with the ``fold``
|
116 |
+
attribute added, if ``fold`` is 1.
|
117 |
+
|
118 |
+
.. versionadded:: 2.6.0
|
119 |
+
"""
|
120 |
+
if getattr(dt, 'fold', 0) == fold:
|
121 |
+
return dt
|
122 |
+
|
123 |
+
args = dt.timetuple()[:6]
|
124 |
+
args += (dt.microsecond, dt.tzinfo)
|
125 |
+
|
126 |
+
if fold:
|
127 |
+
return _DatetimeWithFold(*args)
|
128 |
+
else:
|
129 |
+
return datetime(*args)
|
130 |
+
|
131 |
+
|
132 |
+
def _validate_fromutc_inputs(f):
|
133 |
+
"""
|
134 |
+
The CPython version of ``fromutc`` checks that the input is a ``datetime``
|
135 |
+
object and that ``self`` is attached as its ``tzinfo``.
|
136 |
+
"""
|
137 |
+
@wraps(f)
|
138 |
+
def fromutc(self, dt):
|
139 |
+
if not isinstance(dt, datetime):
|
140 |
+
raise TypeError("fromutc() requires a datetime argument")
|
141 |
+
if dt.tzinfo is not self:
|
142 |
+
raise ValueError("dt.tzinfo is not self")
|
143 |
+
|
144 |
+
return f(self, dt)
|
145 |
+
|
146 |
+
return fromutc
|
147 |
+
|
148 |
+
|
149 |
+
class _tzinfo(tzinfo):
|
150 |
+
"""
|
151 |
+
Base class for all ``dateutil`` ``tzinfo`` objects.
|
152 |
+
"""
|
153 |
+
|
154 |
+
def is_ambiguous(self, dt):
|
155 |
+
"""
|
156 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
157 |
+
zone.
|
158 |
+
|
159 |
+
:param dt:
|
160 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
161 |
+
|
162 |
+
|
163 |
+
:return:
|
164 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
165 |
+
|
166 |
+
.. versionadded:: 2.6.0
|
167 |
+
"""
|
168 |
+
|
169 |
+
dt = dt.replace(tzinfo=self)
|
170 |
+
|
171 |
+
wall_0 = enfold(dt, fold=0)
|
172 |
+
wall_1 = enfold(dt, fold=1)
|
173 |
+
|
174 |
+
same_offset = wall_0.utcoffset() == wall_1.utcoffset()
|
175 |
+
same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None)
|
176 |
+
|
177 |
+
return same_dt and not same_offset
|
178 |
+
|
179 |
+
def _fold_status(self, dt_utc, dt_wall):
|
180 |
+
"""
|
181 |
+
Determine the fold status of a "wall" datetime, given a representation
|
182 |
+
of the same datetime as a (naive) UTC datetime. This is calculated based
|
183 |
+
on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all
|
184 |
+
datetimes, and that this offset is the actual number of hours separating
|
185 |
+
``dt_utc`` and ``dt_wall``.
|
186 |
+
|
187 |
+
:param dt_utc:
|
188 |
+
Representation of the datetime as UTC
|
189 |
+
|
190 |
+
:param dt_wall:
|
191 |
+
Representation of the datetime as "wall time". This parameter must
|
192 |
+
either have a `fold` attribute or have a fold-naive
|
193 |
+
:class:`datetime.tzinfo` attached, otherwise the calculation may
|
194 |
+
fail.
|
195 |
+
"""
|
196 |
+
if self.is_ambiguous(dt_wall):
|
197 |
+
delta_wall = dt_wall - dt_utc
|
198 |
+
_fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst()))
|
199 |
+
else:
|
200 |
+
_fold = 0
|
201 |
+
|
202 |
+
return _fold
|
203 |
+
|
204 |
+
def _fold(self, dt):
|
205 |
+
return getattr(dt, 'fold', 0)
|
206 |
+
|
207 |
+
def _fromutc(self, dt):
|
208 |
+
"""
|
209 |
+
Given a timezone-aware datetime in a given timezone, calculates a
|
210 |
+
timezone-aware datetime in a new timezone.
|
211 |
+
|
212 |
+
Since this is the one time that we *know* we have an unambiguous
|
213 |
+
datetime object, we take this opportunity to determine whether the
|
214 |
+
datetime is ambiguous and in a "fold" state (e.g. if it's the first
|
215 |
+
occurrence, chronologically, of the ambiguous datetime).
|
216 |
+
|
217 |
+
:param dt:
|
218 |
+
A timezone-aware :class:`datetime.datetime` object.
|
219 |
+
"""
|
220 |
+
|
221 |
+
# Re-implement the algorithm from Python's datetime.py
|
222 |
+
dtoff = dt.utcoffset()
|
223 |
+
if dtoff is None:
|
224 |
+
raise ValueError("fromutc() requires a non-None utcoffset() "
|
225 |
+
"result")
|
226 |
+
|
227 |
+
# The original datetime.py code assumes that `dst()` defaults to
|
228 |
+
# zero during ambiguous times. PEP 495 inverts this presumption, so
|
229 |
+
# for pre-PEP 495 versions of python, we need to tweak the algorithm.
|
230 |
+
dtdst = dt.dst()
|
231 |
+
if dtdst is None:
|
232 |
+
raise ValueError("fromutc() requires a non-None dst() result")
|
233 |
+
delta = dtoff - dtdst
|
234 |
+
|
235 |
+
dt += delta
|
236 |
+
# Set fold=1 so we can default to being in the fold for
|
237 |
+
# ambiguous dates.
|
238 |
+
dtdst = enfold(dt, fold=1).dst()
|
239 |
+
if dtdst is None:
|
240 |
+
raise ValueError("fromutc(): dt.dst gave inconsistent "
|
241 |
+
"results; cannot convert")
|
242 |
+
return dt + dtdst
|
243 |
+
|
244 |
+
@_validate_fromutc_inputs
|
245 |
+
def fromutc(self, dt):
|
246 |
+
"""
|
247 |
+
Given a timezone-aware datetime in a given timezone, calculates a
|
248 |
+
timezone-aware datetime in a new timezone.
|
249 |
+
|
250 |
+
Since this is the one time that we *know* we have an unambiguous
|
251 |
+
datetime object, we take this opportunity to determine whether the
|
252 |
+
datetime is ambiguous and in a "fold" state (e.g. if it's the first
|
253 |
+
occurrence, chronologically, of the ambiguous datetime).
|
254 |
+
|
255 |
+
:param dt:
|
256 |
+
A timezone-aware :class:`datetime.datetime` object.
|
257 |
+
"""
|
258 |
+
dt_wall = self._fromutc(dt)
|
259 |
+
|
260 |
+
# Calculate the fold status given the two datetimes.
|
261 |
+
_fold = self._fold_status(dt, dt_wall)
|
262 |
+
|
263 |
+
# Set the default fold value for ambiguous dates
|
264 |
+
return enfold(dt_wall, fold=_fold)
|
265 |
+
|
266 |
+
|
267 |
+
class tzrangebase(_tzinfo):
|
268 |
+
"""
|
269 |
+
This is an abstract base class for time zones represented by an annual
|
270 |
+
transition into and out of DST. Child classes should implement the following
|
271 |
+
methods:
|
272 |
+
|
273 |
+
* ``__init__(self, *args, **kwargs)``
|
274 |
+
* ``transitions(self, year)`` - this is expected to return a tuple of
|
275 |
+
datetimes representing the DST on and off transitions in standard
|
276 |
+
time.
|
277 |
+
|
278 |
+
A fully initialized ``tzrangebase`` subclass should also provide the
|
279 |
+
following attributes:
|
280 |
+
* ``hasdst``: Boolean whether or not the zone uses DST.
|
281 |
+
* ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects
|
282 |
+
representing the respective UTC offsets.
|
283 |
+
* ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short
|
284 |
+
abbreviations in DST and STD, respectively.
|
285 |
+
* ``_hasdst``: Whether or not the zone has DST.
|
286 |
+
|
287 |
+
.. versionadded:: 2.6.0
|
288 |
+
"""
|
289 |
+
def __init__(self):
|
290 |
+
raise NotImplementedError('tzrangebase is an abstract base class')
|
291 |
+
|
292 |
+
def utcoffset(self, dt):
|
293 |
+
isdst = self._isdst(dt)
|
294 |
+
|
295 |
+
if isdst is None:
|
296 |
+
return None
|
297 |
+
elif isdst:
|
298 |
+
return self._dst_offset
|
299 |
+
else:
|
300 |
+
return self._std_offset
|
301 |
+
|
302 |
+
def dst(self, dt):
|
303 |
+
isdst = self._isdst(dt)
|
304 |
+
|
305 |
+
if isdst is None:
|
306 |
+
return None
|
307 |
+
elif isdst:
|
308 |
+
return self._dst_base_offset
|
309 |
+
else:
|
310 |
+
return ZERO
|
311 |
+
|
312 |
+
@tzname_in_python2
|
313 |
+
def tzname(self, dt):
|
314 |
+
if self._isdst(dt):
|
315 |
+
return self._dst_abbr
|
316 |
+
else:
|
317 |
+
return self._std_abbr
|
318 |
+
|
319 |
+
def fromutc(self, dt):
|
320 |
+
""" Given a datetime in UTC, return local time """
|
321 |
+
if not isinstance(dt, datetime):
|
322 |
+
raise TypeError("fromutc() requires a datetime argument")
|
323 |
+
|
324 |
+
if dt.tzinfo is not self:
|
325 |
+
raise ValueError("dt.tzinfo is not self")
|
326 |
+
|
327 |
+
# Get transitions - if there are none, fixed offset
|
328 |
+
transitions = self.transitions(dt.year)
|
329 |
+
if transitions is None:
|
330 |
+
return dt + self.utcoffset(dt)
|
331 |
+
|
332 |
+
# Get the transition times in UTC
|
333 |
+
dston, dstoff = transitions
|
334 |
+
|
335 |
+
dston -= self._std_offset
|
336 |
+
dstoff -= self._std_offset
|
337 |
+
|
338 |
+
utc_transitions = (dston, dstoff)
|
339 |
+
dt_utc = dt.replace(tzinfo=None)
|
340 |
+
|
341 |
+
isdst = self._naive_isdst(dt_utc, utc_transitions)
|
342 |
+
|
343 |
+
if isdst:
|
344 |
+
dt_wall = dt + self._dst_offset
|
345 |
+
else:
|
346 |
+
dt_wall = dt + self._std_offset
|
347 |
+
|
348 |
+
_fold = int(not isdst and self.is_ambiguous(dt_wall))
|
349 |
+
|
350 |
+
return enfold(dt_wall, fold=_fold)
|
351 |
+
|
352 |
+
def is_ambiguous(self, dt):
|
353 |
+
"""
|
354 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
355 |
+
zone.
|
356 |
+
|
357 |
+
:param dt:
|
358 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
359 |
+
|
360 |
+
|
361 |
+
:return:
|
362 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
363 |
+
|
364 |
+
.. versionadded:: 2.6.0
|
365 |
+
"""
|
366 |
+
if not self.hasdst:
|
367 |
+
return False
|
368 |
+
|
369 |
+
start, end = self.transitions(dt.year)
|
370 |
+
|
371 |
+
dt = dt.replace(tzinfo=None)
|
372 |
+
return (end <= dt < end + self._dst_base_offset)
|
373 |
+
|
374 |
+
def _isdst(self, dt):
|
375 |
+
if not self.hasdst:
|
376 |
+
return False
|
377 |
+
elif dt is None:
|
378 |
+
return None
|
379 |
+
|
380 |
+
transitions = self.transitions(dt.year)
|
381 |
+
|
382 |
+
if transitions is None:
|
383 |
+
return False
|
384 |
+
|
385 |
+
dt = dt.replace(tzinfo=None)
|
386 |
+
|
387 |
+
isdst = self._naive_isdst(dt, transitions)
|
388 |
+
|
389 |
+
# Handle ambiguous dates
|
390 |
+
if not isdst and self.is_ambiguous(dt):
|
391 |
+
return not self._fold(dt)
|
392 |
+
else:
|
393 |
+
return isdst
|
394 |
+
|
395 |
+
def _naive_isdst(self, dt, transitions):
|
396 |
+
dston, dstoff = transitions
|
397 |
+
|
398 |
+
dt = dt.replace(tzinfo=None)
|
399 |
+
|
400 |
+
if dston < dstoff:
|
401 |
+
isdst = dston <= dt < dstoff
|
402 |
+
else:
|
403 |
+
isdst = not dstoff <= dt < dston
|
404 |
+
|
405 |
+
return isdst
|
406 |
+
|
407 |
+
@property
|
408 |
+
def _dst_base_offset(self):
|
409 |
+
return self._dst_offset - self._std_offset
|
410 |
+
|
411 |
+
__hash__ = None
|
412 |
+
|
413 |
+
def __ne__(self, other):
|
414 |
+
return not (self == other)
|
415 |
+
|
416 |
+
def __repr__(self):
|
417 |
+
return "%s(...)" % self.__class__.__name__
|
418 |
+
|
419 |
+
__reduce__ = object.__reduce__
|
venv/lib/python3.10/site-packages/dateutil/tz/_factories.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import timedelta
|
2 |
+
import weakref
|
3 |
+
from collections import OrderedDict
|
4 |
+
|
5 |
+
from six.moves import _thread
|
6 |
+
|
7 |
+
|
8 |
+
class _TzSingleton(type):
|
9 |
+
def __init__(cls, *args, **kwargs):
|
10 |
+
cls.__instance = None
|
11 |
+
super(_TzSingleton, cls).__init__(*args, **kwargs)
|
12 |
+
|
13 |
+
def __call__(cls):
|
14 |
+
if cls.__instance is None:
|
15 |
+
cls.__instance = super(_TzSingleton, cls).__call__()
|
16 |
+
return cls.__instance
|
17 |
+
|
18 |
+
|
19 |
+
class _TzFactory(type):
|
20 |
+
def instance(cls, *args, **kwargs):
|
21 |
+
"""Alternate constructor that returns a fresh instance"""
|
22 |
+
return type.__call__(cls, *args, **kwargs)
|
23 |
+
|
24 |
+
|
25 |
+
class _TzOffsetFactory(_TzFactory):
|
26 |
+
def __init__(cls, *args, **kwargs):
|
27 |
+
cls.__instances = weakref.WeakValueDictionary()
|
28 |
+
cls.__strong_cache = OrderedDict()
|
29 |
+
cls.__strong_cache_size = 8
|
30 |
+
|
31 |
+
cls._cache_lock = _thread.allocate_lock()
|
32 |
+
|
33 |
+
def __call__(cls, name, offset):
|
34 |
+
if isinstance(offset, timedelta):
|
35 |
+
key = (name, offset.total_seconds())
|
36 |
+
else:
|
37 |
+
key = (name, offset)
|
38 |
+
|
39 |
+
instance = cls.__instances.get(key, None)
|
40 |
+
if instance is None:
|
41 |
+
instance = cls.__instances.setdefault(key,
|
42 |
+
cls.instance(name, offset))
|
43 |
+
|
44 |
+
# This lock may not be necessary in Python 3. See GH issue #901
|
45 |
+
with cls._cache_lock:
|
46 |
+
cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance)
|
47 |
+
|
48 |
+
# Remove an item if the strong cache is overpopulated
|
49 |
+
if len(cls.__strong_cache) > cls.__strong_cache_size:
|
50 |
+
cls.__strong_cache.popitem(last=False)
|
51 |
+
|
52 |
+
return instance
|
53 |
+
|
54 |
+
|
55 |
+
class _TzStrFactory(_TzFactory):
|
56 |
+
def __init__(cls, *args, **kwargs):
|
57 |
+
cls.__instances = weakref.WeakValueDictionary()
|
58 |
+
cls.__strong_cache = OrderedDict()
|
59 |
+
cls.__strong_cache_size = 8
|
60 |
+
|
61 |
+
cls.__cache_lock = _thread.allocate_lock()
|
62 |
+
|
63 |
+
def __call__(cls, s, posix_offset=False):
|
64 |
+
key = (s, posix_offset)
|
65 |
+
instance = cls.__instances.get(key, None)
|
66 |
+
|
67 |
+
if instance is None:
|
68 |
+
instance = cls.__instances.setdefault(key,
|
69 |
+
cls.instance(s, posix_offset))
|
70 |
+
|
71 |
+
# This lock may not be necessary in Python 3. See GH issue #901
|
72 |
+
with cls.__cache_lock:
|
73 |
+
cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance)
|
74 |
+
|
75 |
+
# Remove an item if the strong cache is overpopulated
|
76 |
+
if len(cls.__strong_cache) > cls.__strong_cache_size:
|
77 |
+
cls.__strong_cache.popitem(last=False)
|
78 |
+
|
79 |
+
return instance
|
80 |
+
|
venv/lib/python3.10/site-packages/dateutil/tz/tz.py
ADDED
@@ -0,0 +1,1849 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
This module offers timezone implementations subclassing the abstract
|
4 |
+
:py:class:`datetime.tzinfo` type. There are classes to handle tzfile format
|
5 |
+
files (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`,
|
6 |
+
etc), TZ environment string (in all known formats), given ranges (with help
|
7 |
+
from relative deltas), local machine timezone, fixed offset timezone, and UTC
|
8 |
+
timezone.
|
9 |
+
"""
|
10 |
+
import datetime
|
11 |
+
import struct
|
12 |
+
import time
|
13 |
+
import sys
|
14 |
+
import os
|
15 |
+
import bisect
|
16 |
+
import weakref
|
17 |
+
from collections import OrderedDict
|
18 |
+
|
19 |
+
import six
|
20 |
+
from six import string_types
|
21 |
+
from six.moves import _thread
|
22 |
+
from ._common import tzname_in_python2, _tzinfo
|
23 |
+
from ._common import tzrangebase, enfold
|
24 |
+
from ._common import _validate_fromutc_inputs
|
25 |
+
|
26 |
+
from ._factories import _TzSingleton, _TzOffsetFactory
|
27 |
+
from ._factories import _TzStrFactory
|
28 |
+
try:
|
29 |
+
from .win import tzwin, tzwinlocal
|
30 |
+
except ImportError:
|
31 |
+
tzwin = tzwinlocal = None
|
32 |
+
|
33 |
+
# For warning about rounding tzinfo
|
34 |
+
from warnings import warn
|
35 |
+
|
36 |
+
ZERO = datetime.timedelta(0)
|
37 |
+
EPOCH = datetime.datetime(1970, 1, 1, 0, 0)
|
38 |
+
EPOCHORDINAL = EPOCH.toordinal()
|
39 |
+
|
40 |
+
|
41 |
+
@six.add_metaclass(_TzSingleton)
|
42 |
+
class tzutc(datetime.tzinfo):
|
43 |
+
"""
|
44 |
+
This is a tzinfo object that represents the UTC time zone.
|
45 |
+
|
46 |
+
**Examples:**
|
47 |
+
|
48 |
+
.. doctest::
|
49 |
+
|
50 |
+
>>> from datetime import *
|
51 |
+
>>> from dateutil.tz import *
|
52 |
+
|
53 |
+
>>> datetime.now()
|
54 |
+
datetime.datetime(2003, 9, 27, 9, 40, 1, 521290)
|
55 |
+
|
56 |
+
>>> datetime.now(tzutc())
|
57 |
+
datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc())
|
58 |
+
|
59 |
+
>>> datetime.now(tzutc()).tzname()
|
60 |
+
'UTC'
|
61 |
+
|
62 |
+
.. versionchanged:: 2.7.0
|
63 |
+
``tzutc()`` is now a singleton, so the result of ``tzutc()`` will
|
64 |
+
always return the same object.
|
65 |
+
|
66 |
+
.. doctest::
|
67 |
+
|
68 |
+
>>> from dateutil.tz import tzutc, UTC
|
69 |
+
>>> tzutc() is tzutc()
|
70 |
+
True
|
71 |
+
>>> tzutc() is UTC
|
72 |
+
True
|
73 |
+
"""
|
74 |
+
def utcoffset(self, dt):
|
75 |
+
return ZERO
|
76 |
+
|
77 |
+
def dst(self, dt):
|
78 |
+
return ZERO
|
79 |
+
|
80 |
+
@tzname_in_python2
|
81 |
+
def tzname(self, dt):
|
82 |
+
return "UTC"
|
83 |
+
|
84 |
+
def is_ambiguous(self, dt):
|
85 |
+
"""
|
86 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
87 |
+
zone.
|
88 |
+
|
89 |
+
:param dt:
|
90 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
91 |
+
|
92 |
+
|
93 |
+
:return:
|
94 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
95 |
+
|
96 |
+
.. versionadded:: 2.6.0
|
97 |
+
"""
|
98 |
+
return False
|
99 |
+
|
100 |
+
@_validate_fromutc_inputs
|
101 |
+
def fromutc(self, dt):
|
102 |
+
"""
|
103 |
+
Fast track version of fromutc() returns the original ``dt`` object for
|
104 |
+
any valid :py:class:`datetime.datetime` object.
|
105 |
+
"""
|
106 |
+
return dt
|
107 |
+
|
108 |
+
def __eq__(self, other):
|
109 |
+
if not isinstance(other, (tzutc, tzoffset)):
|
110 |
+
return NotImplemented
|
111 |
+
|
112 |
+
return (isinstance(other, tzutc) or
|
113 |
+
(isinstance(other, tzoffset) and other._offset == ZERO))
|
114 |
+
|
115 |
+
__hash__ = None
|
116 |
+
|
117 |
+
def __ne__(self, other):
|
118 |
+
return not (self == other)
|
119 |
+
|
120 |
+
def __repr__(self):
|
121 |
+
return "%s()" % self.__class__.__name__
|
122 |
+
|
123 |
+
__reduce__ = object.__reduce__
|
124 |
+
|
125 |
+
|
126 |
+
#: Convenience constant providing a :class:`tzutc()` instance
|
127 |
+
#:
|
128 |
+
#: .. versionadded:: 2.7.0
|
129 |
+
UTC = tzutc()
|
130 |
+
|
131 |
+
|
132 |
+
@six.add_metaclass(_TzOffsetFactory)
|
133 |
+
class tzoffset(datetime.tzinfo):
|
134 |
+
"""
|
135 |
+
A simple class for representing a fixed offset from UTC.
|
136 |
+
|
137 |
+
:param name:
|
138 |
+
The timezone name, to be returned when ``tzname()`` is called.
|
139 |
+
:param offset:
|
140 |
+
The time zone offset in seconds, or (since version 2.6.0, represented
|
141 |
+
as a :py:class:`datetime.timedelta` object).
|
142 |
+
"""
|
143 |
+
def __init__(self, name, offset):
|
144 |
+
self._name = name
|
145 |
+
|
146 |
+
try:
|
147 |
+
# Allow a timedelta
|
148 |
+
offset = offset.total_seconds()
|
149 |
+
except (TypeError, AttributeError):
|
150 |
+
pass
|
151 |
+
|
152 |
+
self._offset = datetime.timedelta(seconds=_get_supported_offset(offset))
|
153 |
+
|
154 |
+
def utcoffset(self, dt):
|
155 |
+
return self._offset
|
156 |
+
|
157 |
+
def dst(self, dt):
|
158 |
+
return ZERO
|
159 |
+
|
160 |
+
@tzname_in_python2
|
161 |
+
def tzname(self, dt):
|
162 |
+
return self._name
|
163 |
+
|
164 |
+
@_validate_fromutc_inputs
|
165 |
+
def fromutc(self, dt):
|
166 |
+
return dt + self._offset
|
167 |
+
|
168 |
+
def is_ambiguous(self, dt):
|
169 |
+
"""
|
170 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
171 |
+
zone.
|
172 |
+
|
173 |
+
:param dt:
|
174 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
175 |
+
:return:
|
176 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
177 |
+
|
178 |
+
.. versionadded:: 2.6.0
|
179 |
+
"""
|
180 |
+
return False
|
181 |
+
|
182 |
+
def __eq__(self, other):
|
183 |
+
if not isinstance(other, tzoffset):
|
184 |
+
return NotImplemented
|
185 |
+
|
186 |
+
return self._offset == other._offset
|
187 |
+
|
188 |
+
__hash__ = None
|
189 |
+
|
190 |
+
def __ne__(self, other):
|
191 |
+
return not (self == other)
|
192 |
+
|
193 |
+
def __repr__(self):
|
194 |
+
return "%s(%s, %s)" % (self.__class__.__name__,
|
195 |
+
repr(self._name),
|
196 |
+
int(self._offset.total_seconds()))
|
197 |
+
|
198 |
+
__reduce__ = object.__reduce__
|
199 |
+
|
200 |
+
|
201 |
+
class tzlocal(_tzinfo):
|
202 |
+
"""
|
203 |
+
A :class:`tzinfo` subclass built around the ``time`` timezone functions.
|
204 |
+
"""
|
205 |
+
def __init__(self):
|
206 |
+
super(tzlocal, self).__init__()
|
207 |
+
|
208 |
+
self._std_offset = datetime.timedelta(seconds=-time.timezone)
|
209 |
+
if time.daylight:
|
210 |
+
self._dst_offset = datetime.timedelta(seconds=-time.altzone)
|
211 |
+
else:
|
212 |
+
self._dst_offset = self._std_offset
|
213 |
+
|
214 |
+
self._dst_saved = self._dst_offset - self._std_offset
|
215 |
+
self._hasdst = bool(self._dst_saved)
|
216 |
+
self._tznames = tuple(time.tzname)
|
217 |
+
|
218 |
+
def utcoffset(self, dt):
|
219 |
+
if dt is None and self._hasdst:
|
220 |
+
return None
|
221 |
+
|
222 |
+
if self._isdst(dt):
|
223 |
+
return self._dst_offset
|
224 |
+
else:
|
225 |
+
return self._std_offset
|
226 |
+
|
227 |
+
def dst(self, dt):
|
228 |
+
if dt is None and self._hasdst:
|
229 |
+
return None
|
230 |
+
|
231 |
+
if self._isdst(dt):
|
232 |
+
return self._dst_offset - self._std_offset
|
233 |
+
else:
|
234 |
+
return ZERO
|
235 |
+
|
236 |
+
@tzname_in_python2
|
237 |
+
def tzname(self, dt):
|
238 |
+
return self._tznames[self._isdst(dt)]
|
239 |
+
|
240 |
+
def is_ambiguous(self, dt):
|
241 |
+
"""
|
242 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
243 |
+
zone.
|
244 |
+
|
245 |
+
:param dt:
|
246 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
247 |
+
|
248 |
+
|
249 |
+
:return:
|
250 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
251 |
+
|
252 |
+
.. versionadded:: 2.6.0
|
253 |
+
"""
|
254 |
+
naive_dst = self._naive_is_dst(dt)
|
255 |
+
return (not naive_dst and
|
256 |
+
(naive_dst != self._naive_is_dst(dt - self._dst_saved)))
|
257 |
+
|
258 |
+
def _naive_is_dst(self, dt):
|
259 |
+
timestamp = _datetime_to_timestamp(dt)
|
260 |
+
return time.localtime(timestamp + time.timezone).tm_isdst
|
261 |
+
|
262 |
+
def _isdst(self, dt, fold_naive=True):
|
263 |
+
# We can't use mktime here. It is unstable when deciding if
|
264 |
+
# the hour near to a change is DST or not.
|
265 |
+
#
|
266 |
+
# timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
|
267 |
+
# dt.minute, dt.second, dt.weekday(), 0, -1))
|
268 |
+
# return time.localtime(timestamp).tm_isdst
|
269 |
+
#
|
270 |
+
# The code above yields the following result:
|
271 |
+
#
|
272 |
+
# >>> import tz, datetime
|
273 |
+
# >>> t = tz.tzlocal()
|
274 |
+
# >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
|
275 |
+
# 'BRDT'
|
276 |
+
# >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
|
277 |
+
# 'BRST'
|
278 |
+
# >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
|
279 |
+
# 'BRST'
|
280 |
+
# >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
|
281 |
+
# 'BRDT'
|
282 |
+
# >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
|
283 |
+
# 'BRDT'
|
284 |
+
#
|
285 |
+
# Here is a more stable implementation:
|
286 |
+
#
|
287 |
+
if not self._hasdst:
|
288 |
+
return False
|
289 |
+
|
290 |
+
# Check for ambiguous times:
|
291 |
+
dstval = self._naive_is_dst(dt)
|
292 |
+
fold = getattr(dt, 'fold', None)
|
293 |
+
|
294 |
+
if self.is_ambiguous(dt):
|
295 |
+
if fold is not None:
|
296 |
+
return not self._fold(dt)
|
297 |
+
else:
|
298 |
+
return True
|
299 |
+
|
300 |
+
return dstval
|
301 |
+
|
302 |
+
def __eq__(self, other):
|
303 |
+
if isinstance(other, tzlocal):
|
304 |
+
return (self._std_offset == other._std_offset and
|
305 |
+
self._dst_offset == other._dst_offset)
|
306 |
+
elif isinstance(other, tzutc):
|
307 |
+
return (not self._hasdst and
|
308 |
+
self._tznames[0] in {'UTC', 'GMT'} and
|
309 |
+
self._std_offset == ZERO)
|
310 |
+
elif isinstance(other, tzoffset):
|
311 |
+
return (not self._hasdst and
|
312 |
+
self._tznames[0] == other._name and
|
313 |
+
self._std_offset == other._offset)
|
314 |
+
else:
|
315 |
+
return NotImplemented
|
316 |
+
|
317 |
+
__hash__ = None
|
318 |
+
|
319 |
+
def __ne__(self, other):
|
320 |
+
return not (self == other)
|
321 |
+
|
322 |
+
def __repr__(self):
|
323 |
+
return "%s()" % self.__class__.__name__
|
324 |
+
|
325 |
+
__reduce__ = object.__reduce__
|
326 |
+
|
327 |
+
|
328 |
+
class _ttinfo(object):
|
329 |
+
__slots__ = ["offset", "delta", "isdst", "abbr",
|
330 |
+
"isstd", "isgmt", "dstoffset"]
|
331 |
+
|
332 |
+
def __init__(self):
|
333 |
+
for attr in self.__slots__:
|
334 |
+
setattr(self, attr, None)
|
335 |
+
|
336 |
+
def __repr__(self):
|
337 |
+
l = []
|
338 |
+
for attr in self.__slots__:
|
339 |
+
value = getattr(self, attr)
|
340 |
+
if value is not None:
|
341 |
+
l.append("%s=%s" % (attr, repr(value)))
|
342 |
+
return "%s(%s)" % (self.__class__.__name__, ", ".join(l))
|
343 |
+
|
344 |
+
def __eq__(self, other):
|
345 |
+
if not isinstance(other, _ttinfo):
|
346 |
+
return NotImplemented
|
347 |
+
|
348 |
+
return (self.offset == other.offset and
|
349 |
+
self.delta == other.delta and
|
350 |
+
self.isdst == other.isdst and
|
351 |
+
self.abbr == other.abbr and
|
352 |
+
self.isstd == other.isstd and
|
353 |
+
self.isgmt == other.isgmt and
|
354 |
+
self.dstoffset == other.dstoffset)
|
355 |
+
|
356 |
+
__hash__ = None
|
357 |
+
|
358 |
+
def __ne__(self, other):
|
359 |
+
return not (self == other)
|
360 |
+
|
361 |
+
def __getstate__(self):
|
362 |
+
state = {}
|
363 |
+
for name in self.__slots__:
|
364 |
+
state[name] = getattr(self, name, None)
|
365 |
+
return state
|
366 |
+
|
367 |
+
def __setstate__(self, state):
|
368 |
+
for name in self.__slots__:
|
369 |
+
if name in state:
|
370 |
+
setattr(self, name, state[name])
|
371 |
+
|
372 |
+
|
373 |
+
class _tzfile(object):
|
374 |
+
"""
|
375 |
+
Lightweight class for holding the relevant transition and time zone
|
376 |
+
information read from binary tzfiles.
|
377 |
+
"""
|
378 |
+
attrs = ['trans_list', 'trans_list_utc', 'trans_idx', 'ttinfo_list',
|
379 |
+
'ttinfo_std', 'ttinfo_dst', 'ttinfo_before', 'ttinfo_first']
|
380 |
+
|
381 |
+
def __init__(self, **kwargs):
|
382 |
+
for attr in self.attrs:
|
383 |
+
setattr(self, attr, kwargs.get(attr, None))
|
384 |
+
|
385 |
+
|
386 |
+
class tzfile(_tzinfo):
|
387 |
+
"""
|
388 |
+
This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)``
|
389 |
+
format timezone files to extract current and historical zone information.
|
390 |
+
|
391 |
+
:param fileobj:
|
392 |
+
This can be an opened file stream or a file name that the time zone
|
393 |
+
information can be read from.
|
394 |
+
|
395 |
+
:param filename:
|
396 |
+
This is an optional parameter specifying the source of the time zone
|
397 |
+
information in the event that ``fileobj`` is a file object. If omitted
|
398 |
+
and ``fileobj`` is a file stream, this parameter will be set either to
|
399 |
+
``fileobj``'s ``name`` attribute or to ``repr(fileobj)``.
|
400 |
+
|
401 |
+
See `Sources for Time Zone and Daylight Saving Time Data
|
402 |
+
<https://data.iana.org/time-zones/tz-link.html>`_ for more information.
|
403 |
+
Time zone files can be compiled from the `IANA Time Zone database files
|
404 |
+
<https://www.iana.org/time-zones>`_ with the `zic time zone compiler
|
405 |
+
<https://www.freebsd.org/cgi/man.cgi?query=zic&sektion=8>`_
|
406 |
+
|
407 |
+
.. note::
|
408 |
+
|
409 |
+
Only construct a ``tzfile`` directly if you have a specific timezone
|
410 |
+
file on disk that you want to read into a Python ``tzinfo`` object.
|
411 |
+
If you want to get a ``tzfile`` representing a specific IANA zone,
|
412 |
+
(e.g. ``'America/New_York'``), you should call
|
413 |
+
:func:`dateutil.tz.gettz` with the zone identifier.
|
414 |
+
|
415 |
+
|
416 |
+
**Examples:**
|
417 |
+
|
418 |
+
Using the US Eastern time zone as an example, we can see that a ``tzfile``
|
419 |
+
provides time zone information for the standard Daylight Saving offsets:
|
420 |
+
|
421 |
+
.. testsetup:: tzfile
|
422 |
+
|
423 |
+
from dateutil.tz import gettz
|
424 |
+
from datetime import datetime
|
425 |
+
|
426 |
+
.. doctest:: tzfile
|
427 |
+
|
428 |
+
>>> NYC = gettz('America/New_York')
|
429 |
+
>>> NYC
|
430 |
+
tzfile('/usr/share/zoneinfo/America/New_York')
|
431 |
+
|
432 |
+
>>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST
|
433 |
+
2016-01-03 00:00:00-05:00
|
434 |
+
|
435 |
+
>>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT
|
436 |
+
2016-07-07 00:00:00-04:00
|
437 |
+
|
438 |
+
|
439 |
+
The ``tzfile`` structure contains a fully history of the time zone,
|
440 |
+
so historical dates will also have the right offsets. For example, before
|
441 |
+
the adoption of the UTC standards, New York used local solar mean time:
|
442 |
+
|
443 |
+
.. doctest:: tzfile
|
444 |
+
|
445 |
+
>>> print(datetime(1901, 4, 12, tzinfo=NYC)) # LMT
|
446 |
+
1901-04-12 00:00:00-04:56
|
447 |
+
|
448 |
+
And during World War II, New York was on "Eastern War Time", which was a
|
449 |
+
state of permanent daylight saving time:
|
450 |
+
|
451 |
+
.. doctest:: tzfile
|
452 |
+
|
453 |
+
>>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT
|
454 |
+
1944-02-07 00:00:00-04:00
|
455 |
+
|
456 |
+
"""
|
457 |
+
|
458 |
+
def __init__(self, fileobj, filename=None):
|
459 |
+
super(tzfile, self).__init__()
|
460 |
+
|
461 |
+
file_opened_here = False
|
462 |
+
if isinstance(fileobj, string_types):
|
463 |
+
self._filename = fileobj
|
464 |
+
fileobj = open(fileobj, 'rb')
|
465 |
+
file_opened_here = True
|
466 |
+
elif filename is not None:
|
467 |
+
self._filename = filename
|
468 |
+
elif hasattr(fileobj, "name"):
|
469 |
+
self._filename = fileobj.name
|
470 |
+
else:
|
471 |
+
self._filename = repr(fileobj)
|
472 |
+
|
473 |
+
if fileobj is not None:
|
474 |
+
if not file_opened_here:
|
475 |
+
fileobj = _nullcontext(fileobj)
|
476 |
+
|
477 |
+
with fileobj as file_stream:
|
478 |
+
tzobj = self._read_tzfile(file_stream)
|
479 |
+
|
480 |
+
self._set_tzdata(tzobj)
|
481 |
+
|
482 |
+
def _set_tzdata(self, tzobj):
|
483 |
+
""" Set the time zone data of this object from a _tzfile object """
|
484 |
+
# Copy the relevant attributes over as private attributes
|
485 |
+
for attr in _tzfile.attrs:
|
486 |
+
setattr(self, '_' + attr, getattr(tzobj, attr))
|
487 |
+
|
488 |
+
def _read_tzfile(self, fileobj):
|
489 |
+
out = _tzfile()
|
490 |
+
|
491 |
+
# From tzfile(5):
|
492 |
+
#
|
493 |
+
# The time zone information files used by tzset(3)
|
494 |
+
# begin with the magic characters "TZif" to identify
|
495 |
+
# them as time zone information files, followed by
|
496 |
+
# sixteen bytes reserved for future use, followed by
|
497 |
+
# six four-byte values of type long, written in a
|
498 |
+
# ``standard'' byte order (the high-order byte
|
499 |
+
# of the value is written first).
|
500 |
+
if fileobj.read(4).decode() != "TZif":
|
501 |
+
raise ValueError("magic not found")
|
502 |
+
|
503 |
+
fileobj.read(16)
|
504 |
+
|
505 |
+
(
|
506 |
+
# The number of UTC/local indicators stored in the file.
|
507 |
+
ttisgmtcnt,
|
508 |
+
|
509 |
+
# The number of standard/wall indicators stored in the file.
|
510 |
+
ttisstdcnt,
|
511 |
+
|
512 |
+
# The number of leap seconds for which data is
|
513 |
+
# stored in the file.
|
514 |
+
leapcnt,
|
515 |
+
|
516 |
+
# The number of "transition times" for which data
|
517 |
+
# is stored in the file.
|
518 |
+
timecnt,
|
519 |
+
|
520 |
+
# The number of "local time types" for which data
|
521 |
+
# is stored in the file (must not be zero).
|
522 |
+
typecnt,
|
523 |
+
|
524 |
+
# The number of characters of "time zone
|
525 |
+
# abbreviation strings" stored in the file.
|
526 |
+
charcnt,
|
527 |
+
|
528 |
+
) = struct.unpack(">6l", fileobj.read(24))
|
529 |
+
|
530 |
+
# The above header is followed by tzh_timecnt four-byte
|
531 |
+
# values of type long, sorted in ascending order.
|
532 |
+
# These values are written in ``standard'' byte order.
|
533 |
+
# Each is used as a transition time (as returned by
|
534 |
+
# time(2)) at which the rules for computing local time
|
535 |
+
# change.
|
536 |
+
|
537 |
+
if timecnt:
|
538 |
+
out.trans_list_utc = list(struct.unpack(">%dl" % timecnt,
|
539 |
+
fileobj.read(timecnt*4)))
|
540 |
+
else:
|
541 |
+
out.trans_list_utc = []
|
542 |
+
|
543 |
+
# Next come tzh_timecnt one-byte values of type unsigned
|
544 |
+
# char; each one tells which of the different types of
|
545 |
+
# ``local time'' types described in the file is associated
|
546 |
+
# with the same-indexed transition time. These values
|
547 |
+
# serve as indices into an array of ttinfo structures that
|
548 |
+
# appears next in the file.
|
549 |
+
|
550 |
+
if timecnt:
|
551 |
+
out.trans_idx = struct.unpack(">%dB" % timecnt,
|
552 |
+
fileobj.read(timecnt))
|
553 |
+
else:
|
554 |
+
out.trans_idx = []
|
555 |
+
|
556 |
+
# Each ttinfo structure is written as a four-byte value
|
557 |
+
# for tt_gmtoff of type long, in a standard byte
|
558 |
+
# order, followed by a one-byte value for tt_isdst
|
559 |
+
# and a one-byte value for tt_abbrind. In each
|
560 |
+
# structure, tt_gmtoff gives the number of
|
561 |
+
# seconds to be added to UTC, tt_isdst tells whether
|
562 |
+
# tm_isdst should be set by localtime(3), and
|
563 |
+
# tt_abbrind serves as an index into the array of
|
564 |
+
# time zone abbreviation characters that follow the
|
565 |
+
# ttinfo structure(s) in the file.
|
566 |
+
|
567 |
+
ttinfo = []
|
568 |
+
|
569 |
+
for i in range(typecnt):
|
570 |
+
ttinfo.append(struct.unpack(">lbb", fileobj.read(6)))
|
571 |
+
|
572 |
+
abbr = fileobj.read(charcnt).decode()
|
573 |
+
|
574 |
+
# Then there are tzh_leapcnt pairs of four-byte
|
575 |
+
# values, written in standard byte order; the
|
576 |
+
# first value of each pair gives the time (as
|
577 |
+
# returned by time(2)) at which a leap second
|
578 |
+
# occurs; the second gives the total number of
|
579 |
+
# leap seconds to be applied after the given time.
|
580 |
+
# The pairs of values are sorted in ascending order
|
581 |
+
# by time.
|
582 |
+
|
583 |
+
# Not used, for now (but seek for correct file position)
|
584 |
+
if leapcnt:
|
585 |
+
fileobj.seek(leapcnt * 8, os.SEEK_CUR)
|
586 |
+
|
587 |
+
# Then there are tzh_ttisstdcnt standard/wall
|
588 |
+
# indicators, each stored as a one-byte value;
|
589 |
+
# they tell whether the transition times associated
|
590 |
+
# with local time types were specified as standard
|
591 |
+
# time or wall clock time, and are used when
|
592 |
+
# a time zone file is used in handling POSIX-style
|
593 |
+
# time zone environment variables.
|
594 |
+
|
595 |
+
if ttisstdcnt:
|
596 |
+
isstd = struct.unpack(">%db" % ttisstdcnt,
|
597 |
+
fileobj.read(ttisstdcnt))
|
598 |
+
|
599 |
+
# Finally, there are tzh_ttisgmtcnt UTC/local
|
600 |
+
# indicators, each stored as a one-byte value;
|
601 |
+
# they tell whether the transition times associated
|
602 |
+
# with local time types were specified as UTC or
|
603 |
+
# local time, and are used when a time zone file
|
604 |
+
# is used in handling POSIX-style time zone envi-
|
605 |
+
# ronment variables.
|
606 |
+
|
607 |
+
if ttisgmtcnt:
|
608 |
+
isgmt = struct.unpack(">%db" % ttisgmtcnt,
|
609 |
+
fileobj.read(ttisgmtcnt))
|
610 |
+
|
611 |
+
# Build ttinfo list
|
612 |
+
out.ttinfo_list = []
|
613 |
+
for i in range(typecnt):
|
614 |
+
gmtoff, isdst, abbrind = ttinfo[i]
|
615 |
+
gmtoff = _get_supported_offset(gmtoff)
|
616 |
+
tti = _ttinfo()
|
617 |
+
tti.offset = gmtoff
|
618 |
+
tti.dstoffset = datetime.timedelta(0)
|
619 |
+
tti.delta = datetime.timedelta(seconds=gmtoff)
|
620 |
+
tti.isdst = isdst
|
621 |
+
tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)]
|
622 |
+
tti.isstd = (ttisstdcnt > i and isstd[i] != 0)
|
623 |
+
tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0)
|
624 |
+
out.ttinfo_list.append(tti)
|
625 |
+
|
626 |
+
# Replace ttinfo indexes for ttinfo objects.
|
627 |
+
out.trans_idx = [out.ttinfo_list[idx] for idx in out.trans_idx]
|
628 |
+
|
629 |
+
# Set standard, dst, and before ttinfos. before will be
|
630 |
+
# used when a given time is before any transitions,
|
631 |
+
# and will be set to the first non-dst ttinfo, or to
|
632 |
+
# the first dst, if all of them are dst.
|
633 |
+
out.ttinfo_std = None
|
634 |
+
out.ttinfo_dst = None
|
635 |
+
out.ttinfo_before = None
|
636 |
+
if out.ttinfo_list:
|
637 |
+
if not out.trans_list_utc:
|
638 |
+
out.ttinfo_std = out.ttinfo_first = out.ttinfo_list[0]
|
639 |
+
else:
|
640 |
+
for i in range(timecnt-1, -1, -1):
|
641 |
+
tti = out.trans_idx[i]
|
642 |
+
if not out.ttinfo_std and not tti.isdst:
|
643 |
+
out.ttinfo_std = tti
|
644 |
+
elif not out.ttinfo_dst and tti.isdst:
|
645 |
+
out.ttinfo_dst = tti
|
646 |
+
|
647 |
+
if out.ttinfo_std and out.ttinfo_dst:
|
648 |
+
break
|
649 |
+
else:
|
650 |
+
if out.ttinfo_dst and not out.ttinfo_std:
|
651 |
+
out.ttinfo_std = out.ttinfo_dst
|
652 |
+
|
653 |
+
for tti in out.ttinfo_list:
|
654 |
+
if not tti.isdst:
|
655 |
+
out.ttinfo_before = tti
|
656 |
+
break
|
657 |
+
else:
|
658 |
+
out.ttinfo_before = out.ttinfo_list[0]
|
659 |
+
|
660 |
+
# Now fix transition times to become relative to wall time.
|
661 |
+
#
|
662 |
+
# I'm not sure about this. In my tests, the tz source file
|
663 |
+
# is setup to wall time, and in the binary file isstd and
|
664 |
+
# isgmt are off, so it should be in wall time. OTOH, it's
|
665 |
+
# always in gmt time. Let me know if you have comments
|
666 |
+
# about this.
|
667 |
+
lastdst = None
|
668 |
+
lastoffset = None
|
669 |
+
lastdstoffset = None
|
670 |
+
lastbaseoffset = None
|
671 |
+
out.trans_list = []
|
672 |
+
|
673 |
+
for i, tti in enumerate(out.trans_idx):
|
674 |
+
offset = tti.offset
|
675 |
+
dstoffset = 0
|
676 |
+
|
677 |
+
if lastdst is not None:
|
678 |
+
if tti.isdst:
|
679 |
+
if not lastdst:
|
680 |
+
dstoffset = offset - lastoffset
|
681 |
+
|
682 |
+
if not dstoffset and lastdstoffset:
|
683 |
+
dstoffset = lastdstoffset
|
684 |
+
|
685 |
+
tti.dstoffset = datetime.timedelta(seconds=dstoffset)
|
686 |
+
lastdstoffset = dstoffset
|
687 |
+
|
688 |
+
# If a time zone changes its base offset during a DST transition,
|
689 |
+
# then you need to adjust by the previous base offset to get the
|
690 |
+
# transition time in local time. Otherwise you use the current
|
691 |
+
# base offset. Ideally, I would have some mathematical proof of
|
692 |
+
# why this is true, but I haven't really thought about it enough.
|
693 |
+
baseoffset = offset - dstoffset
|
694 |
+
adjustment = baseoffset
|
695 |
+
if (lastbaseoffset is not None and baseoffset != lastbaseoffset
|
696 |
+
and tti.isdst != lastdst):
|
697 |
+
# The base DST has changed
|
698 |
+
adjustment = lastbaseoffset
|
699 |
+
|
700 |
+
lastdst = tti.isdst
|
701 |
+
lastoffset = offset
|
702 |
+
lastbaseoffset = baseoffset
|
703 |
+
|
704 |
+
out.trans_list.append(out.trans_list_utc[i] + adjustment)
|
705 |
+
|
706 |
+
out.trans_idx = tuple(out.trans_idx)
|
707 |
+
out.trans_list = tuple(out.trans_list)
|
708 |
+
out.trans_list_utc = tuple(out.trans_list_utc)
|
709 |
+
|
710 |
+
return out
|
711 |
+
|
712 |
+
def _find_last_transition(self, dt, in_utc=False):
|
713 |
+
# If there's no list, there are no transitions to find
|
714 |
+
if not self._trans_list:
|
715 |
+
return None
|
716 |
+
|
717 |
+
timestamp = _datetime_to_timestamp(dt)
|
718 |
+
|
719 |
+
# Find where the timestamp fits in the transition list - if the
|
720 |
+
# timestamp is a transition time, it's part of the "after" period.
|
721 |
+
trans_list = self._trans_list_utc if in_utc else self._trans_list
|
722 |
+
idx = bisect.bisect_right(trans_list, timestamp)
|
723 |
+
|
724 |
+
# We want to know when the previous transition was, so subtract off 1
|
725 |
+
return idx - 1
|
726 |
+
|
727 |
+
def _get_ttinfo(self, idx):
|
728 |
+
# For no list or after the last transition, default to _ttinfo_std
|
729 |
+
if idx is None or (idx + 1) >= len(self._trans_list):
|
730 |
+
return self._ttinfo_std
|
731 |
+
|
732 |
+
# If there is a list and the time is before it, return _ttinfo_before
|
733 |
+
if idx < 0:
|
734 |
+
return self._ttinfo_before
|
735 |
+
|
736 |
+
return self._trans_idx[idx]
|
737 |
+
|
738 |
+
def _find_ttinfo(self, dt):
|
739 |
+
idx = self._resolve_ambiguous_time(dt)
|
740 |
+
|
741 |
+
return self._get_ttinfo(idx)
|
742 |
+
|
743 |
+
def fromutc(self, dt):
|
744 |
+
"""
|
745 |
+
The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`.
|
746 |
+
|
747 |
+
:param dt:
|
748 |
+
A :py:class:`datetime.datetime` object.
|
749 |
+
|
750 |
+
:raises TypeError:
|
751 |
+
Raised if ``dt`` is not a :py:class:`datetime.datetime` object.
|
752 |
+
|
753 |
+
:raises ValueError:
|
754 |
+
Raised if this is called with a ``dt`` which does not have this
|
755 |
+
``tzinfo`` attached.
|
756 |
+
|
757 |
+
:return:
|
758 |
+
Returns a :py:class:`datetime.datetime` object representing the
|
759 |
+
wall time in ``self``'s time zone.
|
760 |
+
"""
|
761 |
+
# These isinstance checks are in datetime.tzinfo, so we'll preserve
|
762 |
+
# them, even if we don't care about duck typing.
|
763 |
+
if not isinstance(dt, datetime.datetime):
|
764 |
+
raise TypeError("fromutc() requires a datetime argument")
|
765 |
+
|
766 |
+
if dt.tzinfo is not self:
|
767 |
+
raise ValueError("dt.tzinfo is not self")
|
768 |
+
|
769 |
+
# First treat UTC as wall time and get the transition we're in.
|
770 |
+
idx = self._find_last_transition(dt, in_utc=True)
|
771 |
+
tti = self._get_ttinfo(idx)
|
772 |
+
|
773 |
+
dt_out = dt + datetime.timedelta(seconds=tti.offset)
|
774 |
+
|
775 |
+
fold = self.is_ambiguous(dt_out, idx=idx)
|
776 |
+
|
777 |
+
return enfold(dt_out, fold=int(fold))
|
778 |
+
|
779 |
+
def is_ambiguous(self, dt, idx=None):
|
780 |
+
"""
|
781 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
782 |
+
zone.
|
783 |
+
|
784 |
+
:param dt:
|
785 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
786 |
+
|
787 |
+
|
788 |
+
:return:
|
789 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
790 |
+
|
791 |
+
.. versionadded:: 2.6.0
|
792 |
+
"""
|
793 |
+
if idx is None:
|
794 |
+
idx = self._find_last_transition(dt)
|
795 |
+
|
796 |
+
# Calculate the difference in offsets from current to previous
|
797 |
+
timestamp = _datetime_to_timestamp(dt)
|
798 |
+
tti = self._get_ttinfo(idx)
|
799 |
+
|
800 |
+
if idx is None or idx <= 0:
|
801 |
+
return False
|
802 |
+
|
803 |
+
od = self._get_ttinfo(idx - 1).offset - tti.offset
|
804 |
+
tt = self._trans_list[idx] # Transition time
|
805 |
+
|
806 |
+
return timestamp < tt + od
|
807 |
+
|
808 |
+
def _resolve_ambiguous_time(self, dt):
|
809 |
+
idx = self._find_last_transition(dt)
|
810 |
+
|
811 |
+
# If we have no transitions, return the index
|
812 |
+
_fold = self._fold(dt)
|
813 |
+
if idx is None or idx == 0:
|
814 |
+
return idx
|
815 |
+
|
816 |
+
# If it's ambiguous and we're in a fold, shift to a different index.
|
817 |
+
idx_offset = int(not _fold and self.is_ambiguous(dt, idx))
|
818 |
+
|
819 |
+
return idx - idx_offset
|
820 |
+
|
821 |
+
def utcoffset(self, dt):
|
822 |
+
if dt is None:
|
823 |
+
return None
|
824 |
+
|
825 |
+
if not self._ttinfo_std:
|
826 |
+
return ZERO
|
827 |
+
|
828 |
+
return self._find_ttinfo(dt).delta
|
829 |
+
|
830 |
+
def dst(self, dt):
|
831 |
+
if dt is None:
|
832 |
+
return None
|
833 |
+
|
834 |
+
if not self._ttinfo_dst:
|
835 |
+
return ZERO
|
836 |
+
|
837 |
+
tti = self._find_ttinfo(dt)
|
838 |
+
|
839 |
+
if not tti.isdst:
|
840 |
+
return ZERO
|
841 |
+
|
842 |
+
# The documentation says that utcoffset()-dst() must
|
843 |
+
# be constant for every dt.
|
844 |
+
return tti.dstoffset
|
845 |
+
|
846 |
+
@tzname_in_python2
|
847 |
+
def tzname(self, dt):
|
848 |
+
if not self._ttinfo_std or dt is None:
|
849 |
+
return None
|
850 |
+
return self._find_ttinfo(dt).abbr
|
851 |
+
|
852 |
+
def __eq__(self, other):
|
853 |
+
if not isinstance(other, tzfile):
|
854 |
+
return NotImplemented
|
855 |
+
return (self._trans_list == other._trans_list and
|
856 |
+
self._trans_idx == other._trans_idx and
|
857 |
+
self._ttinfo_list == other._ttinfo_list)
|
858 |
+
|
859 |
+
__hash__ = None
|
860 |
+
|
861 |
+
def __ne__(self, other):
|
862 |
+
return not (self == other)
|
863 |
+
|
864 |
+
def __repr__(self):
|
865 |
+
return "%s(%s)" % (self.__class__.__name__, repr(self._filename))
|
866 |
+
|
867 |
+
def __reduce__(self):
|
868 |
+
return self.__reduce_ex__(None)
|
869 |
+
|
870 |
+
def __reduce_ex__(self, protocol):
|
871 |
+
return (self.__class__, (None, self._filename), self.__dict__)
|
872 |
+
|
873 |
+
|
874 |
+
class tzrange(tzrangebase):
|
875 |
+
"""
|
876 |
+
The ``tzrange`` object is a time zone specified by a set of offsets and
|
877 |
+
abbreviations, equivalent to the way the ``TZ`` variable can be specified
|
878 |
+
in POSIX-like systems, but using Python delta objects to specify DST
|
879 |
+
start, end and offsets.
|
880 |
+
|
881 |
+
:param stdabbr:
|
882 |
+
The abbreviation for standard time (e.g. ``'EST'``).
|
883 |
+
|
884 |
+
:param stdoffset:
|
885 |
+
An integer or :class:`datetime.timedelta` object or equivalent
|
886 |
+
specifying the base offset from UTC.
|
887 |
+
|
888 |
+
If unspecified, +00:00 is used.
|
889 |
+
|
890 |
+
:param dstabbr:
|
891 |
+
The abbreviation for DST / "Summer" time (e.g. ``'EDT'``).
|
892 |
+
|
893 |
+
If specified, with no other DST information, DST is assumed to occur
|
894 |
+
and the default behavior or ``dstoffset``, ``start`` and ``end`` is
|
895 |
+
used. If unspecified and no other DST information is specified, it
|
896 |
+
is assumed that this zone has no DST.
|
897 |
+
|
898 |
+
If this is unspecified and other DST information is *is* specified,
|
899 |
+
DST occurs in the zone but the time zone abbreviation is left
|
900 |
+
unchanged.
|
901 |
+
|
902 |
+
:param dstoffset:
|
903 |
+
A an integer or :class:`datetime.timedelta` object or equivalent
|
904 |
+
specifying the UTC offset during DST. If unspecified and any other DST
|
905 |
+
information is specified, it is assumed to be the STD offset +1 hour.
|
906 |
+
|
907 |
+
:param start:
|
908 |
+
A :class:`relativedelta.relativedelta` object or equivalent specifying
|
909 |
+
the time and time of year that daylight savings time starts. To
|
910 |
+
specify, for example, that DST starts at 2AM on the 2nd Sunday in
|
911 |
+
March, pass:
|
912 |
+
|
913 |
+
``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))``
|
914 |
+
|
915 |
+
If unspecified and any other DST information is specified, the default
|
916 |
+
value is 2 AM on the first Sunday in April.
|
917 |
+
|
918 |
+
:param end:
|
919 |
+
A :class:`relativedelta.relativedelta` object or equivalent
|
920 |
+
representing the time and time of year that daylight savings time
|
921 |
+
ends, with the same specification method as in ``start``. One note is
|
922 |
+
that this should point to the first time in the *standard* zone, so if
|
923 |
+
a transition occurs at 2AM in the DST zone and the clocks are set back
|
924 |
+
1 hour to 1AM, set the ``hours`` parameter to +1.
|
925 |
+
|
926 |
+
|
927 |
+
**Examples:**
|
928 |
+
|
929 |
+
.. testsetup:: tzrange
|
930 |
+
|
931 |
+
from dateutil.tz import tzrange, tzstr
|
932 |
+
|
933 |
+
.. doctest:: tzrange
|
934 |
+
|
935 |
+
>>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT")
|
936 |
+
True
|
937 |
+
|
938 |
+
>>> from dateutil.relativedelta import *
|
939 |
+
>>> range1 = tzrange("EST", -18000, "EDT")
|
940 |
+
>>> range2 = tzrange("EST", -18000, "EDT", -14400,
|
941 |
+
... relativedelta(hours=+2, month=4, day=1,
|
942 |
+
... weekday=SU(+1)),
|
943 |
+
... relativedelta(hours=+1, month=10, day=31,
|
944 |
+
... weekday=SU(-1)))
|
945 |
+
>>> tzstr('EST5EDT') == range1 == range2
|
946 |
+
True
|
947 |
+
|
948 |
+
"""
|
949 |
+
def __init__(self, stdabbr, stdoffset=None,
|
950 |
+
dstabbr=None, dstoffset=None,
|
951 |
+
start=None, end=None):
|
952 |
+
|
953 |
+
global relativedelta
|
954 |
+
from dateutil import relativedelta
|
955 |
+
|
956 |
+
self._std_abbr = stdabbr
|
957 |
+
self._dst_abbr = dstabbr
|
958 |
+
|
959 |
+
try:
|
960 |
+
stdoffset = stdoffset.total_seconds()
|
961 |
+
except (TypeError, AttributeError):
|
962 |
+
pass
|
963 |
+
|
964 |
+
try:
|
965 |
+
dstoffset = dstoffset.total_seconds()
|
966 |
+
except (TypeError, AttributeError):
|
967 |
+
pass
|
968 |
+
|
969 |
+
if stdoffset is not None:
|
970 |
+
self._std_offset = datetime.timedelta(seconds=stdoffset)
|
971 |
+
else:
|
972 |
+
self._std_offset = ZERO
|
973 |
+
|
974 |
+
if dstoffset is not None:
|
975 |
+
self._dst_offset = datetime.timedelta(seconds=dstoffset)
|
976 |
+
elif dstabbr and stdoffset is not None:
|
977 |
+
self._dst_offset = self._std_offset + datetime.timedelta(hours=+1)
|
978 |
+
else:
|
979 |
+
self._dst_offset = ZERO
|
980 |
+
|
981 |
+
if dstabbr and start is None:
|
982 |
+
self._start_delta = relativedelta.relativedelta(
|
983 |
+
hours=+2, month=4, day=1, weekday=relativedelta.SU(+1))
|
984 |
+
else:
|
985 |
+
self._start_delta = start
|
986 |
+
|
987 |
+
if dstabbr and end is None:
|
988 |
+
self._end_delta = relativedelta.relativedelta(
|
989 |
+
hours=+1, month=10, day=31, weekday=relativedelta.SU(-1))
|
990 |
+
else:
|
991 |
+
self._end_delta = end
|
992 |
+
|
993 |
+
self._dst_base_offset_ = self._dst_offset - self._std_offset
|
994 |
+
self.hasdst = bool(self._start_delta)
|
995 |
+
|
996 |
+
def transitions(self, year):
|
997 |
+
"""
|
998 |
+
For a given year, get the DST on and off transition times, expressed
|
999 |
+
always on the standard time side. For zones with no transitions, this
|
1000 |
+
function returns ``None``.
|
1001 |
+
|
1002 |
+
:param year:
|
1003 |
+
The year whose transitions you would like to query.
|
1004 |
+
|
1005 |
+
:return:
|
1006 |
+
Returns a :class:`tuple` of :class:`datetime.datetime` objects,
|
1007 |
+
``(dston, dstoff)`` for zones with an annual DST transition, or
|
1008 |
+
``None`` for fixed offset zones.
|
1009 |
+
"""
|
1010 |
+
if not self.hasdst:
|
1011 |
+
return None
|
1012 |
+
|
1013 |
+
base_year = datetime.datetime(year, 1, 1)
|
1014 |
+
|
1015 |
+
start = base_year + self._start_delta
|
1016 |
+
end = base_year + self._end_delta
|
1017 |
+
|
1018 |
+
return (start, end)
|
1019 |
+
|
1020 |
+
def __eq__(self, other):
|
1021 |
+
if not isinstance(other, tzrange):
|
1022 |
+
return NotImplemented
|
1023 |
+
|
1024 |
+
return (self._std_abbr == other._std_abbr and
|
1025 |
+
self._dst_abbr == other._dst_abbr and
|
1026 |
+
self._std_offset == other._std_offset and
|
1027 |
+
self._dst_offset == other._dst_offset and
|
1028 |
+
self._start_delta == other._start_delta and
|
1029 |
+
self._end_delta == other._end_delta)
|
1030 |
+
|
1031 |
+
@property
|
1032 |
+
def _dst_base_offset(self):
|
1033 |
+
return self._dst_base_offset_
|
1034 |
+
|
1035 |
+
|
1036 |
+
@six.add_metaclass(_TzStrFactory)
|
1037 |
+
class tzstr(tzrange):
|
1038 |
+
"""
|
1039 |
+
``tzstr`` objects are time zone objects specified by a time-zone string as
|
1040 |
+
it would be passed to a ``TZ`` variable on POSIX-style systems (see
|
1041 |
+
the `GNU C Library: TZ Variable`_ for more details).
|
1042 |
+
|
1043 |
+
There is one notable exception, which is that POSIX-style time zones use an
|
1044 |
+
inverted offset format, so normally ``GMT+3`` would be parsed as an offset
|
1045 |
+
3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an
|
1046 |
+
offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX
|
1047 |
+
behavior, pass a ``True`` value to ``posix_offset``.
|
1048 |
+
|
1049 |
+
The :class:`tzrange` object provides the same functionality, but is
|
1050 |
+
specified using :class:`relativedelta.relativedelta` objects. rather than
|
1051 |
+
strings.
|
1052 |
+
|
1053 |
+
:param s:
|
1054 |
+
A time zone string in ``TZ`` variable format. This can be a
|
1055 |
+
:class:`bytes` (2.x: :class:`str`), :class:`str` (2.x:
|
1056 |
+
:class:`unicode`) or a stream emitting unicode characters
|
1057 |
+
(e.g. :class:`StringIO`).
|
1058 |
+
|
1059 |
+
:param posix_offset:
|
1060 |
+
Optional. If set to ``True``, interpret strings such as ``GMT+3`` or
|
1061 |
+
``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the
|
1062 |
+
POSIX standard.
|
1063 |
+
|
1064 |
+
.. caution::
|
1065 |
+
|
1066 |
+
Prior to version 2.7.0, this function also supported time zones
|
1067 |
+
in the format:
|
1068 |
+
|
1069 |
+
* ``EST5EDT,4,0,6,7200,10,0,26,7200,3600``
|
1070 |
+
* ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600``
|
1071 |
+
|
1072 |
+
This format is non-standard and has been deprecated; this function
|
1073 |
+
will raise a :class:`DeprecatedTZFormatWarning` until
|
1074 |
+
support is removed in a future version.
|
1075 |
+
|
1076 |
+
.. _`GNU C Library: TZ Variable`:
|
1077 |
+
https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
|
1078 |
+
"""
|
1079 |
+
def __init__(self, s, posix_offset=False):
|
1080 |
+
global parser
|
1081 |
+
from dateutil.parser import _parser as parser
|
1082 |
+
|
1083 |
+
self._s = s
|
1084 |
+
|
1085 |
+
res = parser._parsetz(s)
|
1086 |
+
if res is None or res.any_unused_tokens:
|
1087 |
+
raise ValueError("unknown string format")
|
1088 |
+
|
1089 |
+
# Here we break the compatibility with the TZ variable handling.
|
1090 |
+
# GMT-3 actually *means* the timezone -3.
|
1091 |
+
if res.stdabbr in ("GMT", "UTC") and not posix_offset:
|
1092 |
+
res.stdoffset *= -1
|
1093 |
+
|
1094 |
+
# We must initialize it first, since _delta() needs
|
1095 |
+
# _std_offset and _dst_offset set. Use False in start/end
|
1096 |
+
# to avoid building it two times.
|
1097 |
+
tzrange.__init__(self, res.stdabbr, res.stdoffset,
|
1098 |
+
res.dstabbr, res.dstoffset,
|
1099 |
+
start=False, end=False)
|
1100 |
+
|
1101 |
+
if not res.dstabbr:
|
1102 |
+
self._start_delta = None
|
1103 |
+
self._end_delta = None
|
1104 |
+
else:
|
1105 |
+
self._start_delta = self._delta(res.start)
|
1106 |
+
if self._start_delta:
|
1107 |
+
self._end_delta = self._delta(res.end, isend=1)
|
1108 |
+
|
1109 |
+
self.hasdst = bool(self._start_delta)
|
1110 |
+
|
1111 |
+
def _delta(self, x, isend=0):
|
1112 |
+
from dateutil import relativedelta
|
1113 |
+
kwargs = {}
|
1114 |
+
if x.month is not None:
|
1115 |
+
kwargs["month"] = x.month
|
1116 |
+
if x.weekday is not None:
|
1117 |
+
kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week)
|
1118 |
+
if x.week > 0:
|
1119 |
+
kwargs["day"] = 1
|
1120 |
+
else:
|
1121 |
+
kwargs["day"] = 31
|
1122 |
+
elif x.day:
|
1123 |
+
kwargs["day"] = x.day
|
1124 |
+
elif x.yday is not None:
|
1125 |
+
kwargs["yearday"] = x.yday
|
1126 |
+
elif x.jyday is not None:
|
1127 |
+
kwargs["nlyearday"] = x.jyday
|
1128 |
+
if not kwargs:
|
1129 |
+
# Default is to start on first sunday of april, and end
|
1130 |
+
# on last sunday of october.
|
1131 |
+
if not isend:
|
1132 |
+
kwargs["month"] = 4
|
1133 |
+
kwargs["day"] = 1
|
1134 |
+
kwargs["weekday"] = relativedelta.SU(+1)
|
1135 |
+
else:
|
1136 |
+
kwargs["month"] = 10
|
1137 |
+
kwargs["day"] = 31
|
1138 |
+
kwargs["weekday"] = relativedelta.SU(-1)
|
1139 |
+
if x.time is not None:
|
1140 |
+
kwargs["seconds"] = x.time
|
1141 |
+
else:
|
1142 |
+
# Default is 2AM.
|
1143 |
+
kwargs["seconds"] = 7200
|
1144 |
+
if isend:
|
1145 |
+
# Convert to standard time, to follow the documented way
|
1146 |
+
# of working with the extra hour. See the documentation
|
1147 |
+
# of the tzinfo class.
|
1148 |
+
delta = self._dst_offset - self._std_offset
|
1149 |
+
kwargs["seconds"] -= delta.seconds + delta.days * 86400
|
1150 |
+
return relativedelta.relativedelta(**kwargs)
|
1151 |
+
|
1152 |
+
def __repr__(self):
|
1153 |
+
return "%s(%s)" % (self.__class__.__name__, repr(self._s))
|
1154 |
+
|
1155 |
+
|
1156 |
+
class _tzicalvtzcomp(object):
|
1157 |
+
def __init__(self, tzoffsetfrom, tzoffsetto, isdst,
|
1158 |
+
tzname=None, rrule=None):
|
1159 |
+
self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom)
|
1160 |
+
self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto)
|
1161 |
+
self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom
|
1162 |
+
self.isdst = isdst
|
1163 |
+
self.tzname = tzname
|
1164 |
+
self.rrule = rrule
|
1165 |
+
|
1166 |
+
|
1167 |
+
class _tzicalvtz(_tzinfo):
|
1168 |
+
def __init__(self, tzid, comps=[]):
|
1169 |
+
super(_tzicalvtz, self).__init__()
|
1170 |
+
|
1171 |
+
self._tzid = tzid
|
1172 |
+
self._comps = comps
|
1173 |
+
self._cachedate = []
|
1174 |
+
self._cachecomp = []
|
1175 |
+
self._cache_lock = _thread.allocate_lock()
|
1176 |
+
|
1177 |
+
def _find_comp(self, dt):
|
1178 |
+
if len(self._comps) == 1:
|
1179 |
+
return self._comps[0]
|
1180 |
+
|
1181 |
+
dt = dt.replace(tzinfo=None)
|
1182 |
+
|
1183 |
+
try:
|
1184 |
+
with self._cache_lock:
|
1185 |
+
return self._cachecomp[self._cachedate.index(
|
1186 |
+
(dt, self._fold(dt)))]
|
1187 |
+
except ValueError:
|
1188 |
+
pass
|
1189 |
+
|
1190 |
+
lastcompdt = None
|
1191 |
+
lastcomp = None
|
1192 |
+
|
1193 |
+
for comp in self._comps:
|
1194 |
+
compdt = self._find_compdt(comp, dt)
|
1195 |
+
|
1196 |
+
if compdt and (not lastcompdt or lastcompdt < compdt):
|
1197 |
+
lastcompdt = compdt
|
1198 |
+
lastcomp = comp
|
1199 |
+
|
1200 |
+
if not lastcomp:
|
1201 |
+
# RFC says nothing about what to do when a given
|
1202 |
+
# time is before the first onset date. We'll look for the
|
1203 |
+
# first standard component, or the first component, if
|
1204 |
+
# none is found.
|
1205 |
+
for comp in self._comps:
|
1206 |
+
if not comp.isdst:
|
1207 |
+
lastcomp = comp
|
1208 |
+
break
|
1209 |
+
else:
|
1210 |
+
lastcomp = comp[0]
|
1211 |
+
|
1212 |
+
with self._cache_lock:
|
1213 |
+
self._cachedate.insert(0, (dt, self._fold(dt)))
|
1214 |
+
self._cachecomp.insert(0, lastcomp)
|
1215 |
+
|
1216 |
+
if len(self._cachedate) > 10:
|
1217 |
+
self._cachedate.pop()
|
1218 |
+
self._cachecomp.pop()
|
1219 |
+
|
1220 |
+
return lastcomp
|
1221 |
+
|
1222 |
+
def _find_compdt(self, comp, dt):
|
1223 |
+
if comp.tzoffsetdiff < ZERO and self._fold(dt):
|
1224 |
+
dt -= comp.tzoffsetdiff
|
1225 |
+
|
1226 |
+
compdt = comp.rrule.before(dt, inc=True)
|
1227 |
+
|
1228 |
+
return compdt
|
1229 |
+
|
1230 |
+
def utcoffset(self, dt):
|
1231 |
+
if dt is None:
|
1232 |
+
return None
|
1233 |
+
|
1234 |
+
return self._find_comp(dt).tzoffsetto
|
1235 |
+
|
1236 |
+
def dst(self, dt):
|
1237 |
+
comp = self._find_comp(dt)
|
1238 |
+
if comp.isdst:
|
1239 |
+
return comp.tzoffsetdiff
|
1240 |
+
else:
|
1241 |
+
return ZERO
|
1242 |
+
|
1243 |
+
@tzname_in_python2
|
1244 |
+
def tzname(self, dt):
|
1245 |
+
return self._find_comp(dt).tzname
|
1246 |
+
|
1247 |
+
def __repr__(self):
|
1248 |
+
return "<tzicalvtz %s>" % repr(self._tzid)
|
1249 |
+
|
1250 |
+
__reduce__ = object.__reduce__
|
1251 |
+
|
1252 |
+
|
1253 |
+
class tzical(object):
|
1254 |
+
"""
|
1255 |
+
This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure
|
1256 |
+
as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects.
|
1257 |
+
|
1258 |
+
:param `fileobj`:
|
1259 |
+
A file or stream in iCalendar format, which should be UTF-8 encoded
|
1260 |
+
with CRLF endings.
|
1261 |
+
|
1262 |
+
.. _`RFC 5545`: https://tools.ietf.org/html/rfc5545
|
1263 |
+
"""
|
1264 |
+
def __init__(self, fileobj):
|
1265 |
+
global rrule
|
1266 |
+
from dateutil import rrule
|
1267 |
+
|
1268 |
+
if isinstance(fileobj, string_types):
|
1269 |
+
self._s = fileobj
|
1270 |
+
# ical should be encoded in UTF-8 with CRLF
|
1271 |
+
fileobj = open(fileobj, 'r')
|
1272 |
+
else:
|
1273 |
+
self._s = getattr(fileobj, 'name', repr(fileobj))
|
1274 |
+
fileobj = _nullcontext(fileobj)
|
1275 |
+
|
1276 |
+
self._vtz = {}
|
1277 |
+
|
1278 |
+
with fileobj as fobj:
|
1279 |
+
self._parse_rfc(fobj.read())
|
1280 |
+
|
1281 |
+
def keys(self):
|
1282 |
+
"""
|
1283 |
+
Retrieves the available time zones as a list.
|
1284 |
+
"""
|
1285 |
+
return list(self._vtz.keys())
|
1286 |
+
|
1287 |
+
def get(self, tzid=None):
|
1288 |
+
"""
|
1289 |
+
Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``.
|
1290 |
+
|
1291 |
+
:param tzid:
|
1292 |
+
If there is exactly one time zone available, omitting ``tzid``
|
1293 |
+
or passing :py:const:`None` value returns it. Otherwise a valid
|
1294 |
+
key (which can be retrieved from :func:`keys`) is required.
|
1295 |
+
|
1296 |
+
:raises ValueError:
|
1297 |
+
Raised if ``tzid`` is not specified but there are either more
|
1298 |
+
or fewer than 1 zone defined.
|
1299 |
+
|
1300 |
+
:returns:
|
1301 |
+
Returns either a :py:class:`datetime.tzinfo` object representing
|
1302 |
+
the relevant time zone or :py:const:`None` if the ``tzid`` was
|
1303 |
+
not found.
|
1304 |
+
"""
|
1305 |
+
if tzid is None:
|
1306 |
+
if len(self._vtz) == 0:
|
1307 |
+
raise ValueError("no timezones defined")
|
1308 |
+
elif len(self._vtz) > 1:
|
1309 |
+
raise ValueError("more than one timezone available")
|
1310 |
+
tzid = next(iter(self._vtz))
|
1311 |
+
|
1312 |
+
return self._vtz.get(tzid)
|
1313 |
+
|
1314 |
+
def _parse_offset(self, s):
|
1315 |
+
s = s.strip()
|
1316 |
+
if not s:
|
1317 |
+
raise ValueError("empty offset")
|
1318 |
+
if s[0] in ('+', '-'):
|
1319 |
+
signal = (-1, +1)[s[0] == '+']
|
1320 |
+
s = s[1:]
|
1321 |
+
else:
|
1322 |
+
signal = +1
|
1323 |
+
if len(s) == 4:
|
1324 |
+
return (int(s[:2]) * 3600 + int(s[2:]) * 60) * signal
|
1325 |
+
elif len(s) == 6:
|
1326 |
+
return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal
|
1327 |
+
else:
|
1328 |
+
raise ValueError("invalid offset: " + s)
|
1329 |
+
|
1330 |
+
def _parse_rfc(self, s):
|
1331 |
+
lines = s.splitlines()
|
1332 |
+
if not lines:
|
1333 |
+
raise ValueError("empty string")
|
1334 |
+
|
1335 |
+
# Unfold
|
1336 |
+
i = 0
|
1337 |
+
while i < len(lines):
|
1338 |
+
line = lines[i].rstrip()
|
1339 |
+
if not line:
|
1340 |
+
del lines[i]
|
1341 |
+
elif i > 0 and line[0] == " ":
|
1342 |
+
lines[i-1] += line[1:]
|
1343 |
+
del lines[i]
|
1344 |
+
else:
|
1345 |
+
i += 1
|
1346 |
+
|
1347 |
+
tzid = None
|
1348 |
+
comps = []
|
1349 |
+
invtz = False
|
1350 |
+
comptype = None
|
1351 |
+
for line in lines:
|
1352 |
+
if not line:
|
1353 |
+
continue
|
1354 |
+
name, value = line.split(':', 1)
|
1355 |
+
parms = name.split(';')
|
1356 |
+
if not parms:
|
1357 |
+
raise ValueError("empty property name")
|
1358 |
+
name = parms[0].upper()
|
1359 |
+
parms = parms[1:]
|
1360 |
+
if invtz:
|
1361 |
+
if name == "BEGIN":
|
1362 |
+
if value in ("STANDARD", "DAYLIGHT"):
|
1363 |
+
# Process component
|
1364 |
+
pass
|
1365 |
+
else:
|
1366 |
+
raise ValueError("unknown component: "+value)
|
1367 |
+
comptype = value
|
1368 |
+
founddtstart = False
|
1369 |
+
tzoffsetfrom = None
|
1370 |
+
tzoffsetto = None
|
1371 |
+
rrulelines = []
|
1372 |
+
tzname = None
|
1373 |
+
elif name == "END":
|
1374 |
+
if value == "VTIMEZONE":
|
1375 |
+
if comptype:
|
1376 |
+
raise ValueError("component not closed: "+comptype)
|
1377 |
+
if not tzid:
|
1378 |
+
raise ValueError("mandatory TZID not found")
|
1379 |
+
if not comps:
|
1380 |
+
raise ValueError(
|
1381 |
+
"at least one component is needed")
|
1382 |
+
# Process vtimezone
|
1383 |
+
self._vtz[tzid] = _tzicalvtz(tzid, comps)
|
1384 |
+
invtz = False
|
1385 |
+
elif value == comptype:
|
1386 |
+
if not founddtstart:
|
1387 |
+
raise ValueError("mandatory DTSTART not found")
|
1388 |
+
if tzoffsetfrom is None:
|
1389 |
+
raise ValueError(
|
1390 |
+
"mandatory TZOFFSETFROM not found")
|
1391 |
+
if tzoffsetto is None:
|
1392 |
+
raise ValueError(
|
1393 |
+
"mandatory TZOFFSETFROM not found")
|
1394 |
+
# Process component
|
1395 |
+
rr = None
|
1396 |
+
if rrulelines:
|
1397 |
+
rr = rrule.rrulestr("\n".join(rrulelines),
|
1398 |
+
compatible=True,
|
1399 |
+
ignoretz=True,
|
1400 |
+
cache=True)
|
1401 |
+
comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto,
|
1402 |
+
(comptype == "DAYLIGHT"),
|
1403 |
+
tzname, rr)
|
1404 |
+
comps.append(comp)
|
1405 |
+
comptype = None
|
1406 |
+
else:
|
1407 |
+
raise ValueError("invalid component end: "+value)
|
1408 |
+
elif comptype:
|
1409 |
+
if name == "DTSTART":
|
1410 |
+
# DTSTART in VTIMEZONE takes a subset of valid RRULE
|
1411 |
+
# values under RFC 5545.
|
1412 |
+
for parm in parms:
|
1413 |
+
if parm != 'VALUE=DATE-TIME':
|
1414 |
+
msg = ('Unsupported DTSTART param in ' +
|
1415 |
+
'VTIMEZONE: ' + parm)
|
1416 |
+
raise ValueError(msg)
|
1417 |
+
rrulelines.append(line)
|
1418 |
+
founddtstart = True
|
1419 |
+
elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"):
|
1420 |
+
rrulelines.append(line)
|
1421 |
+
elif name == "TZOFFSETFROM":
|
1422 |
+
if parms:
|
1423 |
+
raise ValueError(
|
1424 |
+
"unsupported %s parm: %s " % (name, parms[0]))
|
1425 |
+
tzoffsetfrom = self._parse_offset(value)
|
1426 |
+
elif name == "TZOFFSETTO":
|
1427 |
+
if parms:
|
1428 |
+
raise ValueError(
|
1429 |
+
"unsupported TZOFFSETTO parm: "+parms[0])
|
1430 |
+
tzoffsetto = self._parse_offset(value)
|
1431 |
+
elif name == "TZNAME":
|
1432 |
+
if parms:
|
1433 |
+
raise ValueError(
|
1434 |
+
"unsupported TZNAME parm: "+parms[0])
|
1435 |
+
tzname = value
|
1436 |
+
elif name == "COMMENT":
|
1437 |
+
pass
|
1438 |
+
else:
|
1439 |
+
raise ValueError("unsupported property: "+name)
|
1440 |
+
else:
|
1441 |
+
if name == "TZID":
|
1442 |
+
if parms:
|
1443 |
+
raise ValueError(
|
1444 |
+
"unsupported TZID parm: "+parms[0])
|
1445 |
+
tzid = value
|
1446 |
+
elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"):
|
1447 |
+
pass
|
1448 |
+
else:
|
1449 |
+
raise ValueError("unsupported property: "+name)
|
1450 |
+
elif name == "BEGIN" and value == "VTIMEZONE":
|
1451 |
+
tzid = None
|
1452 |
+
comps = []
|
1453 |
+
invtz = True
|
1454 |
+
|
1455 |
+
def __repr__(self):
|
1456 |
+
return "%s(%s)" % (self.__class__.__name__, repr(self._s))
|
1457 |
+
|
1458 |
+
|
1459 |
+
if sys.platform != "win32":
|
1460 |
+
TZFILES = ["/etc/localtime", "localtime"]
|
1461 |
+
TZPATHS = ["/usr/share/zoneinfo",
|
1462 |
+
"/usr/lib/zoneinfo",
|
1463 |
+
"/usr/share/lib/zoneinfo",
|
1464 |
+
"/etc/zoneinfo"]
|
1465 |
+
else:
|
1466 |
+
TZFILES = []
|
1467 |
+
TZPATHS = []
|
1468 |
+
|
1469 |
+
|
1470 |
+
def __get_gettz():
|
1471 |
+
tzlocal_classes = (tzlocal,)
|
1472 |
+
if tzwinlocal is not None:
|
1473 |
+
tzlocal_classes += (tzwinlocal,)
|
1474 |
+
|
1475 |
+
class GettzFunc(object):
|
1476 |
+
"""
|
1477 |
+
Retrieve a time zone object from a string representation
|
1478 |
+
|
1479 |
+
This function is intended to retrieve the :py:class:`tzinfo` subclass
|
1480 |
+
that best represents the time zone that would be used if a POSIX
|
1481 |
+
`TZ variable`_ were set to the same value.
|
1482 |
+
|
1483 |
+
If no argument or an empty string is passed to ``gettz``, local time
|
1484 |
+
is returned:
|
1485 |
+
|
1486 |
+
.. code-block:: python3
|
1487 |
+
|
1488 |
+
>>> gettz()
|
1489 |
+
tzfile('/etc/localtime')
|
1490 |
+
|
1491 |
+
This function is also the preferred way to map IANA tz database keys
|
1492 |
+
to :class:`tzfile` objects:
|
1493 |
+
|
1494 |
+
.. code-block:: python3
|
1495 |
+
|
1496 |
+
>>> gettz('Pacific/Kiritimati')
|
1497 |
+
tzfile('/usr/share/zoneinfo/Pacific/Kiritimati')
|
1498 |
+
|
1499 |
+
On Windows, the standard is extended to include the Windows-specific
|
1500 |
+
zone names provided by the operating system:
|
1501 |
+
|
1502 |
+
.. code-block:: python3
|
1503 |
+
|
1504 |
+
>>> gettz('Egypt Standard Time')
|
1505 |
+
tzwin('Egypt Standard Time')
|
1506 |
+
|
1507 |
+
Passing a GNU ``TZ`` style string time zone specification returns a
|
1508 |
+
:class:`tzstr` object:
|
1509 |
+
|
1510 |
+
.. code-block:: python3
|
1511 |
+
|
1512 |
+
>>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3')
|
1513 |
+
tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3')
|
1514 |
+
|
1515 |
+
:param name:
|
1516 |
+
A time zone name (IANA, or, on Windows, Windows keys), location of
|
1517 |
+
a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone
|
1518 |
+
specifier. An empty string, no argument or ``None`` is interpreted
|
1519 |
+
as local time.
|
1520 |
+
|
1521 |
+
:return:
|
1522 |
+
Returns an instance of one of ``dateutil``'s :py:class:`tzinfo`
|
1523 |
+
subclasses.
|
1524 |
+
|
1525 |
+
.. versionchanged:: 2.7.0
|
1526 |
+
|
1527 |
+
After version 2.7.0, any two calls to ``gettz`` using the same
|
1528 |
+
input strings will return the same object:
|
1529 |
+
|
1530 |
+
.. code-block:: python3
|
1531 |
+
|
1532 |
+
>>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago')
|
1533 |
+
True
|
1534 |
+
|
1535 |
+
In addition to improving performance, this ensures that
|
1536 |
+
`"same zone" semantics`_ are used for datetimes in the same zone.
|
1537 |
+
|
1538 |
+
|
1539 |
+
.. _`TZ variable`:
|
1540 |
+
https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
|
1541 |
+
|
1542 |
+
.. _`"same zone" semantics`:
|
1543 |
+
https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html
|
1544 |
+
"""
|
1545 |
+
def __init__(self):
|
1546 |
+
|
1547 |
+
self.__instances = weakref.WeakValueDictionary()
|
1548 |
+
self.__strong_cache_size = 8
|
1549 |
+
self.__strong_cache = OrderedDict()
|
1550 |
+
self._cache_lock = _thread.allocate_lock()
|
1551 |
+
|
1552 |
+
def __call__(self, name=None):
|
1553 |
+
with self._cache_lock:
|
1554 |
+
rv = self.__instances.get(name, None)
|
1555 |
+
|
1556 |
+
if rv is None:
|
1557 |
+
rv = self.nocache(name=name)
|
1558 |
+
if not (name is None
|
1559 |
+
or isinstance(rv, tzlocal_classes)
|
1560 |
+
or rv is None):
|
1561 |
+
# tzlocal is slightly more complicated than the other
|
1562 |
+
# time zone providers because it depends on environment
|
1563 |
+
# at construction time, so don't cache that.
|
1564 |
+
#
|
1565 |
+
# We also cannot store weak references to None, so we
|
1566 |
+
# will also not store that.
|
1567 |
+
self.__instances[name] = rv
|
1568 |
+
else:
|
1569 |
+
# No need for strong caching, return immediately
|
1570 |
+
return rv
|
1571 |
+
|
1572 |
+
self.__strong_cache[name] = self.__strong_cache.pop(name, rv)
|
1573 |
+
|
1574 |
+
if len(self.__strong_cache) > self.__strong_cache_size:
|
1575 |
+
self.__strong_cache.popitem(last=False)
|
1576 |
+
|
1577 |
+
return rv
|
1578 |
+
|
1579 |
+
def set_cache_size(self, size):
|
1580 |
+
with self._cache_lock:
|
1581 |
+
self.__strong_cache_size = size
|
1582 |
+
while len(self.__strong_cache) > size:
|
1583 |
+
self.__strong_cache.popitem(last=False)
|
1584 |
+
|
1585 |
+
def cache_clear(self):
|
1586 |
+
with self._cache_lock:
|
1587 |
+
self.__instances = weakref.WeakValueDictionary()
|
1588 |
+
self.__strong_cache.clear()
|
1589 |
+
|
1590 |
+
@staticmethod
|
1591 |
+
def nocache(name=None):
|
1592 |
+
"""A non-cached version of gettz"""
|
1593 |
+
tz = None
|
1594 |
+
if not name:
|
1595 |
+
try:
|
1596 |
+
name = os.environ["TZ"]
|
1597 |
+
except KeyError:
|
1598 |
+
pass
|
1599 |
+
if name is None or name in ("", ":"):
|
1600 |
+
for filepath in TZFILES:
|
1601 |
+
if not os.path.isabs(filepath):
|
1602 |
+
filename = filepath
|
1603 |
+
for path in TZPATHS:
|
1604 |
+
filepath = os.path.join(path, filename)
|
1605 |
+
if os.path.isfile(filepath):
|
1606 |
+
break
|
1607 |
+
else:
|
1608 |
+
continue
|
1609 |
+
if os.path.isfile(filepath):
|
1610 |
+
try:
|
1611 |
+
tz = tzfile(filepath)
|
1612 |
+
break
|
1613 |
+
except (IOError, OSError, ValueError):
|
1614 |
+
pass
|
1615 |
+
else:
|
1616 |
+
tz = tzlocal()
|
1617 |
+
else:
|
1618 |
+
try:
|
1619 |
+
if name.startswith(":"):
|
1620 |
+
name = name[1:]
|
1621 |
+
except TypeError as e:
|
1622 |
+
if isinstance(name, bytes):
|
1623 |
+
new_msg = "gettz argument should be str, not bytes"
|
1624 |
+
six.raise_from(TypeError(new_msg), e)
|
1625 |
+
else:
|
1626 |
+
raise
|
1627 |
+
if os.path.isabs(name):
|
1628 |
+
if os.path.isfile(name):
|
1629 |
+
tz = tzfile(name)
|
1630 |
+
else:
|
1631 |
+
tz = None
|
1632 |
+
else:
|
1633 |
+
for path in TZPATHS:
|
1634 |
+
filepath = os.path.join(path, name)
|
1635 |
+
if not os.path.isfile(filepath):
|
1636 |
+
filepath = filepath.replace(' ', '_')
|
1637 |
+
if not os.path.isfile(filepath):
|
1638 |
+
continue
|
1639 |
+
try:
|
1640 |
+
tz = tzfile(filepath)
|
1641 |
+
break
|
1642 |
+
except (IOError, OSError, ValueError):
|
1643 |
+
pass
|
1644 |
+
else:
|
1645 |
+
tz = None
|
1646 |
+
if tzwin is not None:
|
1647 |
+
try:
|
1648 |
+
tz = tzwin(name)
|
1649 |
+
except (WindowsError, UnicodeEncodeError):
|
1650 |
+
# UnicodeEncodeError is for Python 2.7 compat
|
1651 |
+
tz = None
|
1652 |
+
|
1653 |
+
if not tz:
|
1654 |
+
from dateutil.zoneinfo import get_zonefile_instance
|
1655 |
+
tz = get_zonefile_instance().get(name)
|
1656 |
+
|
1657 |
+
if not tz:
|
1658 |
+
for c in name:
|
1659 |
+
# name is not a tzstr unless it has at least
|
1660 |
+
# one offset. For short values of "name", an
|
1661 |
+
# explicit for loop seems to be the fastest way
|
1662 |
+
# To determine if a string contains a digit
|
1663 |
+
if c in "0123456789":
|
1664 |
+
try:
|
1665 |
+
tz = tzstr(name)
|
1666 |
+
except ValueError:
|
1667 |
+
pass
|
1668 |
+
break
|
1669 |
+
else:
|
1670 |
+
if name in ("GMT", "UTC"):
|
1671 |
+
tz = UTC
|
1672 |
+
elif name in time.tzname:
|
1673 |
+
tz = tzlocal()
|
1674 |
+
return tz
|
1675 |
+
|
1676 |
+
return GettzFunc()
|
1677 |
+
|
1678 |
+
|
1679 |
+
gettz = __get_gettz()
|
1680 |
+
del __get_gettz
|
1681 |
+
|
1682 |
+
|
1683 |
+
def datetime_exists(dt, tz=None):
|
1684 |
+
"""
|
1685 |
+
Given a datetime and a time zone, determine whether or not a given datetime
|
1686 |
+
would fall in a gap.
|
1687 |
+
|
1688 |
+
:param dt:
|
1689 |
+
A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``
|
1690 |
+
is provided.)
|
1691 |
+
|
1692 |
+
:param tz:
|
1693 |
+
A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If
|
1694 |
+
``None`` or not provided, the datetime's own time zone will be used.
|
1695 |
+
|
1696 |
+
:return:
|
1697 |
+
Returns a boolean value whether or not the "wall time" exists in
|
1698 |
+
``tz``.
|
1699 |
+
|
1700 |
+
.. versionadded:: 2.7.0
|
1701 |
+
"""
|
1702 |
+
if tz is None:
|
1703 |
+
if dt.tzinfo is None:
|
1704 |
+
raise ValueError('Datetime is naive and no time zone provided.')
|
1705 |
+
tz = dt.tzinfo
|
1706 |
+
|
1707 |
+
dt = dt.replace(tzinfo=None)
|
1708 |
+
|
1709 |
+
# This is essentially a test of whether or not the datetime can survive
|
1710 |
+
# a round trip to UTC.
|
1711 |
+
dt_rt = dt.replace(tzinfo=tz).astimezone(UTC).astimezone(tz)
|
1712 |
+
dt_rt = dt_rt.replace(tzinfo=None)
|
1713 |
+
|
1714 |
+
return dt == dt_rt
|
1715 |
+
|
1716 |
+
|
1717 |
+
def datetime_ambiguous(dt, tz=None):
|
1718 |
+
"""
|
1719 |
+
Given a datetime and a time zone, determine whether or not a given datetime
|
1720 |
+
is ambiguous (i.e if there are two times differentiated only by their DST
|
1721 |
+
status).
|
1722 |
+
|
1723 |
+
:param dt:
|
1724 |
+
A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``
|
1725 |
+
is provided.)
|
1726 |
+
|
1727 |
+
:param tz:
|
1728 |
+
A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If
|
1729 |
+
``None`` or not provided, the datetime's own time zone will be used.
|
1730 |
+
|
1731 |
+
:return:
|
1732 |
+
Returns a boolean value whether or not the "wall time" is ambiguous in
|
1733 |
+
``tz``.
|
1734 |
+
|
1735 |
+
.. versionadded:: 2.6.0
|
1736 |
+
"""
|
1737 |
+
if tz is None:
|
1738 |
+
if dt.tzinfo is None:
|
1739 |
+
raise ValueError('Datetime is naive and no time zone provided.')
|
1740 |
+
|
1741 |
+
tz = dt.tzinfo
|
1742 |
+
|
1743 |
+
# If a time zone defines its own "is_ambiguous" function, we'll use that.
|
1744 |
+
is_ambiguous_fn = getattr(tz, 'is_ambiguous', None)
|
1745 |
+
if is_ambiguous_fn is not None:
|
1746 |
+
try:
|
1747 |
+
return tz.is_ambiguous(dt)
|
1748 |
+
except Exception:
|
1749 |
+
pass
|
1750 |
+
|
1751 |
+
# If it doesn't come out and tell us it's ambiguous, we'll just check if
|
1752 |
+
# the fold attribute has any effect on this particular date and time.
|
1753 |
+
dt = dt.replace(tzinfo=tz)
|
1754 |
+
wall_0 = enfold(dt, fold=0)
|
1755 |
+
wall_1 = enfold(dt, fold=1)
|
1756 |
+
|
1757 |
+
same_offset = wall_0.utcoffset() == wall_1.utcoffset()
|
1758 |
+
same_dst = wall_0.dst() == wall_1.dst()
|
1759 |
+
|
1760 |
+
return not (same_offset and same_dst)
|
1761 |
+
|
1762 |
+
|
1763 |
+
def resolve_imaginary(dt):
|
1764 |
+
"""
|
1765 |
+
Given a datetime that may be imaginary, return an existing datetime.
|
1766 |
+
|
1767 |
+
This function assumes that an imaginary datetime represents what the
|
1768 |
+
wall time would be in a zone had the offset transition not occurred, so
|
1769 |
+
it will always fall forward by the transition's change in offset.
|
1770 |
+
|
1771 |
+
.. doctest::
|
1772 |
+
|
1773 |
+
>>> from dateutil import tz
|
1774 |
+
>>> from datetime import datetime
|
1775 |
+
>>> NYC = tz.gettz('America/New_York')
|
1776 |
+
>>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC)))
|
1777 |
+
2017-03-12 03:30:00-04:00
|
1778 |
+
|
1779 |
+
>>> KIR = tz.gettz('Pacific/Kiritimati')
|
1780 |
+
>>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR)))
|
1781 |
+
1995-01-02 12:30:00+14:00
|
1782 |
+
|
1783 |
+
As a note, :func:`datetime.astimezone` is guaranteed to produce a valid,
|
1784 |
+
existing datetime, so a round-trip to and from UTC is sufficient to get
|
1785 |
+
an extant datetime, however, this generally "falls back" to an earlier time
|
1786 |
+
rather than falling forward to the STD side (though no guarantees are made
|
1787 |
+
about this behavior).
|
1788 |
+
|
1789 |
+
:param dt:
|
1790 |
+
A :class:`datetime.datetime` which may or may not exist.
|
1791 |
+
|
1792 |
+
:return:
|
1793 |
+
Returns an existing :class:`datetime.datetime`. If ``dt`` was not
|
1794 |
+
imaginary, the datetime returned is guaranteed to be the same object
|
1795 |
+
passed to the function.
|
1796 |
+
|
1797 |
+
.. versionadded:: 2.7.0
|
1798 |
+
"""
|
1799 |
+
if dt.tzinfo is not None and not datetime_exists(dt):
|
1800 |
+
|
1801 |
+
curr_offset = (dt + datetime.timedelta(hours=24)).utcoffset()
|
1802 |
+
old_offset = (dt - datetime.timedelta(hours=24)).utcoffset()
|
1803 |
+
|
1804 |
+
dt += curr_offset - old_offset
|
1805 |
+
|
1806 |
+
return dt
|
1807 |
+
|
1808 |
+
|
1809 |
+
def _datetime_to_timestamp(dt):
|
1810 |
+
"""
|
1811 |
+
Convert a :class:`datetime.datetime` object to an epoch timestamp in
|
1812 |
+
seconds since January 1, 1970, ignoring the time zone.
|
1813 |
+
"""
|
1814 |
+
return (dt.replace(tzinfo=None) - EPOCH).total_seconds()
|
1815 |
+
|
1816 |
+
|
1817 |
+
if sys.version_info >= (3, 6):
|
1818 |
+
def _get_supported_offset(second_offset):
|
1819 |
+
return second_offset
|
1820 |
+
else:
|
1821 |
+
def _get_supported_offset(second_offset):
|
1822 |
+
# For python pre-3.6, round to full-minutes if that's not the case.
|
1823 |
+
# Python's datetime doesn't accept sub-minute timezones. Check
|
1824 |
+
# http://python.org/sf/1447945 or https://bugs.python.org/issue5288
|
1825 |
+
# for some information.
|
1826 |
+
old_offset = second_offset
|
1827 |
+
calculated_offset = 60 * ((second_offset + 30) // 60)
|
1828 |
+
return calculated_offset
|
1829 |
+
|
1830 |
+
|
1831 |
+
try:
|
1832 |
+
# Python 3.7 feature
|
1833 |
+
from contextlib import nullcontext as _nullcontext
|
1834 |
+
except ImportError:
|
1835 |
+
class _nullcontext(object):
|
1836 |
+
"""
|
1837 |
+
Class for wrapping contexts so that they are passed through in a
|
1838 |
+
with statement.
|
1839 |
+
"""
|
1840 |
+
def __init__(self, context):
|
1841 |
+
self.context = context
|
1842 |
+
|
1843 |
+
def __enter__(self):
|
1844 |
+
return self.context
|
1845 |
+
|
1846 |
+
def __exit__(*args, **kwargs):
|
1847 |
+
pass
|
1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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
This module provides an interface to the native time zone data on Windows,
|
4 |
+
including :py:class:`datetime.tzinfo` implementations.
|
5 |
+
|
6 |
+
Attempting to import this module on a non-Windows platform will raise an
|
7 |
+
:py:obj:`ImportError`.
|
8 |
+
"""
|
9 |
+
# This code was originally contributed by Jeffrey Harris.
|
10 |
+
import datetime
|
11 |
+
import struct
|
12 |
+
|
13 |
+
from six.moves import winreg
|
14 |
+
from six import text_type
|
15 |
+
|
16 |
+
try:
|
17 |
+
import ctypes
|
18 |
+
from ctypes import wintypes
|
19 |
+
except ValueError:
|
20 |
+
# ValueError is raised on non-Windows systems for some horrible reason.
|
21 |
+
raise ImportError("Running tzwin on non-Windows system")
|
22 |
+
|
23 |
+
from ._common import tzrangebase
|
24 |
+
|
25 |
+
__all__ = ["tzwin", "tzwinlocal", "tzres"]
|
26 |
+
|
27 |
+
ONEWEEK = datetime.timedelta(7)
|
28 |
+
|
29 |
+
TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"
|
30 |
+
TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones"
|
31 |
+
TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
|
32 |
+
|
33 |
+
|
34 |
+
def _settzkeyname():
|
35 |
+
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
|
36 |
+
try:
|
37 |
+
winreg.OpenKey(handle, TZKEYNAMENT).Close()
|
38 |
+
TZKEYNAME = TZKEYNAMENT
|
39 |
+
except WindowsError:
|
40 |
+
TZKEYNAME = TZKEYNAME9X
|
41 |
+
handle.Close()
|
42 |
+
return TZKEYNAME
|
43 |
+
|
44 |
+
|
45 |
+
TZKEYNAME = _settzkeyname()
|
46 |
+
|
47 |
+
|
48 |
+
class tzres(object):
|
49 |
+
"""
|
50 |
+
Class for accessing ``tzres.dll``, which contains timezone name related
|
51 |
+
resources.
|
52 |
+
|
53 |
+
.. versionadded:: 2.5.0
|
54 |
+
"""
|
55 |
+
p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char
|
56 |
+
|
57 |
+
def __init__(self, tzres_loc='tzres.dll'):
|
58 |
+
# Load the user32 DLL so we can load strings from tzres
|
59 |
+
user32 = ctypes.WinDLL('user32')
|
60 |
+
|
61 |
+
# Specify the LoadStringW function
|
62 |
+
user32.LoadStringW.argtypes = (wintypes.HINSTANCE,
|
63 |
+
wintypes.UINT,
|
64 |
+
wintypes.LPWSTR,
|
65 |
+
ctypes.c_int)
|
66 |
+
|
67 |
+
self.LoadStringW = user32.LoadStringW
|
68 |
+
self._tzres = ctypes.WinDLL(tzres_loc)
|
69 |
+
self.tzres_loc = tzres_loc
|
70 |
+
|
71 |
+
def load_name(self, offset):
|
72 |
+
"""
|
73 |
+
Load a timezone name from a DLL offset (integer).
|
74 |
+
|
75 |
+
>>> from dateutil.tzwin import tzres
|
76 |
+
>>> tzr = tzres()
|
77 |
+
>>> print(tzr.load_name(112))
|
78 |
+
'Eastern Standard Time'
|
79 |
+
|
80 |
+
:param offset:
|
81 |
+
A positive integer value referring to a string from the tzres dll.
|
82 |
+
|
83 |
+
.. note::
|
84 |
+
|
85 |
+
Offsets found in the registry are generally of the form
|
86 |
+
``@tzres.dll,-114``. The offset in this case is 114, not -114.
|
87 |
+
|
88 |
+
"""
|
89 |
+
resource = self.p_wchar()
|
90 |
+
lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR)
|
91 |
+
nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0)
|
92 |
+
return resource[:nchar]
|
93 |
+
|
94 |
+
def name_from_string(self, tzname_str):
|
95 |
+
"""
|
96 |
+
Parse strings as returned from the Windows registry into the time zone
|
97 |
+
name as defined in the registry.
|
98 |
+
|
99 |
+
>>> from dateutil.tzwin import tzres
|
100 |
+
>>> tzr = tzres()
|
101 |
+
>>> print(tzr.name_from_string('@tzres.dll,-251'))
|
102 |
+
'Dateline Daylight Time'
|
103 |
+
>>> print(tzr.name_from_string('Eastern Standard Time'))
|
104 |
+
'Eastern Standard Time'
|
105 |
+
|
106 |
+
:param tzname_str:
|
107 |
+
A timezone name string as returned from a Windows registry key.
|
108 |
+
|
109 |
+
:return:
|
110 |
+
Returns the localized timezone string from tzres.dll if the string
|
111 |
+
is of the form `@tzres.dll,-offset`, else returns the input string.
|
112 |
+
"""
|
113 |
+
if not tzname_str.startswith('@'):
|
114 |
+
return tzname_str
|
115 |
+
|
116 |
+
name_splt = tzname_str.split(',-')
|
117 |
+
try:
|
118 |
+
offset = int(name_splt[1])
|
119 |
+
except:
|
120 |
+
raise ValueError("Malformed timezone string.")
|
121 |
+
|
122 |
+
return self.load_name(offset)
|
123 |
+
|
124 |
+
|
125 |
+
class tzwinbase(tzrangebase):
|
126 |
+
"""tzinfo class based on win32's timezones available in the registry."""
|
127 |
+
def __init__(self):
|
128 |
+
raise NotImplementedError('tzwinbase is an abstract base class')
|
129 |
+
|
130 |
+
def __eq__(self, other):
|
131 |
+
# Compare on all relevant dimensions, including name.
|
132 |
+
if not isinstance(other, tzwinbase):
|
133 |
+
return NotImplemented
|
134 |
+
|
135 |
+
return (self._std_offset == other._std_offset and
|
136 |
+
self._dst_offset == other._dst_offset and
|
137 |
+
self._stddayofweek == other._stddayofweek and
|
138 |
+
self._dstdayofweek == other._dstdayofweek and
|
139 |
+
self._stdweeknumber == other._stdweeknumber and
|
140 |
+
self._dstweeknumber == other._dstweeknumber and
|
141 |
+
self._stdhour == other._stdhour and
|
142 |
+
self._dsthour == other._dsthour and
|
143 |
+
self._stdminute == other._stdminute and
|
144 |
+
self._dstminute == other._dstminute and
|
145 |
+
self._std_abbr == other._std_abbr and
|
146 |
+
self._dst_abbr == other._dst_abbr)
|
147 |
+
|
148 |
+
@staticmethod
|
149 |
+
def list():
|
150 |
+
"""Return a list of all time zones known to the system."""
|
151 |
+
with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
|
152 |
+
with winreg.OpenKey(handle, TZKEYNAME) as tzkey:
|
153 |
+
result = [winreg.EnumKey(tzkey, i)
|
154 |
+
for i in range(winreg.QueryInfoKey(tzkey)[0])]
|
155 |
+
return result
|
156 |
+
|
157 |
+
def display(self):
|
158 |
+
"""
|
159 |
+
Return the display name of the time zone.
|
160 |
+
"""
|
161 |
+
return self._display
|
162 |
+
|
163 |
+
def transitions(self, year):
|
164 |
+
"""
|
165 |
+
For a given year, get the DST on and off transition times, expressed
|
166 |
+
always on the standard time side. For zones with no transitions, this
|
167 |
+
function returns ``None``.
|
168 |
+
|
169 |
+
:param year:
|
170 |
+
The year whose transitions you would like to query.
|
171 |
+
|
172 |
+
:return:
|
173 |
+
Returns a :class:`tuple` of :class:`datetime.datetime` objects,
|
174 |
+
``(dston, dstoff)`` for zones with an annual DST transition, or
|
175 |
+
``None`` for fixed offset zones.
|
176 |
+
"""
|
177 |
+
|
178 |
+
if not self.hasdst:
|
179 |
+
return None
|
180 |
+
|
181 |
+
dston = picknthweekday(year, self._dstmonth, self._dstdayofweek,
|
182 |
+
self._dsthour, self._dstminute,
|
183 |
+
self._dstweeknumber)
|
184 |
+
|
185 |
+
dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek,
|
186 |
+
self._stdhour, self._stdminute,
|
187 |
+
self._stdweeknumber)
|
188 |
+
|
189 |
+
# Ambiguous dates default to the STD side
|
190 |
+
dstoff -= self._dst_base_offset
|
191 |
+
|
192 |
+
return dston, dstoff
|
193 |
+
|
194 |
+
def _get_hasdst(self):
|
195 |
+
return self._dstmonth != 0
|
196 |
+
|
197 |
+
@property
|
198 |
+
def _dst_base_offset(self):
|
199 |
+
return self._dst_base_offset_
|
200 |
+
|
201 |
+
|
202 |
+
class tzwin(tzwinbase):
|
203 |
+
"""
|
204 |
+
Time zone object created from the zone info in the Windows registry
|
205 |
+
|
206 |
+
These are similar to :py:class:`dateutil.tz.tzrange` objects in that
|
207 |
+
the time zone data is provided in the format of a single offset rule
|
208 |
+
for either 0 or 2 time zone transitions per year.
|
209 |
+
|
210 |
+
:param: name
|
211 |
+
The name of a Windows time zone key, e.g. "Eastern Standard Time".
|
212 |
+
The full list of keys can be retrieved with :func:`tzwin.list`.
|
213 |
+
"""
|
214 |
+
|
215 |
+
def __init__(self, name):
|
216 |
+
self._name = name
|
217 |
+
|
218 |
+
with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
|
219 |
+
tzkeyname = text_type("{kn}\\{name}").format(kn=TZKEYNAME, name=name)
|
220 |
+
with winreg.OpenKey(handle, tzkeyname) as tzkey:
|
221 |
+
keydict = valuestodict(tzkey)
|
222 |
+
|
223 |
+
self._std_abbr = keydict["Std"]
|
224 |
+
self._dst_abbr = keydict["Dlt"]
|
225 |
+
|
226 |
+
self._display = keydict["Display"]
|
227 |
+
|
228 |
+
# See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
|
229 |
+
tup = struct.unpack("=3l16h", keydict["TZI"])
|
230 |
+
stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1
|
231 |
+
dstoffset = stdoffset-tup[2] # + DaylightBias * -1
|
232 |
+
self._std_offset = datetime.timedelta(minutes=stdoffset)
|
233 |
+
self._dst_offset = datetime.timedelta(minutes=dstoffset)
|
234 |
+
|
235 |
+
# for the meaning see the win32 TIME_ZONE_INFORMATION structure docs
|
236 |
+
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx
|
237 |
+
(self._stdmonth,
|
238 |
+
self._stddayofweek, # Sunday = 0
|
239 |
+
self._stdweeknumber, # Last = 5
|
240 |
+
self._stdhour,
|
241 |
+
self._stdminute) = tup[4:9]
|
242 |
+
|
243 |
+
(self._dstmonth,
|
244 |
+
self._dstdayofweek, # Sunday = 0
|
245 |
+
self._dstweeknumber, # Last = 5
|
246 |
+
self._dsthour,
|
247 |
+
self._dstminute) = tup[12:17]
|
248 |
+
|
249 |
+
self._dst_base_offset_ = self._dst_offset - self._std_offset
|
250 |
+
self.hasdst = self._get_hasdst()
|
251 |
+
|
252 |
+
def __repr__(self):
|
253 |
+
return "tzwin(%s)" % repr(self._name)
|
254 |
+
|
255 |
+
def __reduce__(self):
|
256 |
+
return (self.__class__, (self._name,))
|
257 |
+
|
258 |
+
|
259 |
+
class tzwinlocal(tzwinbase):
|
260 |
+
"""
|
261 |
+
Class representing the local time zone information in the Windows registry
|
262 |
+
|
263 |
+
While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time`
|
264 |
+
module) to retrieve time zone information, ``tzwinlocal`` retrieves the
|
265 |
+
rules directly from the Windows registry and creates an object like
|
266 |
+
:class:`dateutil.tz.tzwin`.
|
267 |
+
|
268 |
+
Because Windows does not have an equivalent of :func:`time.tzset`, on
|
269 |
+
Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the
|
270 |
+
time zone settings *at the time that the process was started*, meaning
|
271 |
+
changes to the machine's time zone settings during the run of a program
|
272 |
+
on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`.
|
273 |
+
Because ``tzwinlocal`` reads the registry directly, it is unaffected by
|
274 |
+
this issue.
|
275 |
+
"""
|
276 |
+
def __init__(self):
|
277 |
+
with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
|
278 |
+
with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey:
|
279 |
+
keydict = valuestodict(tzlocalkey)
|
280 |
+
|
281 |
+
self._std_abbr = keydict["StandardName"]
|
282 |
+
self._dst_abbr = keydict["DaylightName"]
|
283 |
+
|
284 |
+
try:
|
285 |
+
tzkeyname = text_type('{kn}\\{sn}').format(kn=TZKEYNAME,
|
286 |
+
sn=self._std_abbr)
|
287 |
+
with winreg.OpenKey(handle, tzkeyname) as tzkey:
|
288 |
+
_keydict = valuestodict(tzkey)
|
289 |
+
self._display = _keydict["Display"]
|
290 |
+
except OSError:
|
291 |
+
self._display = None
|
292 |
+
|
293 |
+
stdoffset = -keydict["Bias"]-keydict["StandardBias"]
|
294 |
+
dstoffset = stdoffset-keydict["DaylightBias"]
|
295 |
+
|
296 |
+
self._std_offset = datetime.timedelta(minutes=stdoffset)
|
297 |
+
self._dst_offset = datetime.timedelta(minutes=dstoffset)
|
298 |
+
|
299 |
+
# For reasons unclear, in this particular key, the day of week has been
|
300 |
+
# moved to the END of the SYSTEMTIME structure.
|
301 |
+
tup = struct.unpack("=8h", keydict["StandardStart"])
|
302 |
+
|
303 |
+
(self._stdmonth,
|
304 |
+
self._stdweeknumber, # Last = 5
|
305 |
+
self._stdhour,
|
306 |
+
self._stdminute) = tup[1:5]
|
307 |
+
|
308 |
+
self._stddayofweek = tup[7]
|
309 |
+
|
310 |
+
tup = struct.unpack("=8h", keydict["DaylightStart"])
|
311 |
+
|
312 |
+
(self._dstmonth,
|
313 |
+
self._dstweeknumber, # Last = 5
|
314 |
+
self._dsthour,
|
315 |
+
self._dstminute) = tup[1:5]
|
316 |
+
|
317 |
+
self._dstdayofweek = tup[7]
|
318 |
+
|
319 |
+
self._dst_base_offset_ = self._dst_offset - self._std_offset
|
320 |
+
self.hasdst = self._get_hasdst()
|
321 |
+
|
322 |
+
def __repr__(self):
|
323 |
+
return "tzwinlocal()"
|
324 |
+
|
325 |
+
def __str__(self):
|
326 |
+
# str will return the standard name, not the daylight name.
|
327 |
+
return "tzwinlocal(%s)" % repr(self._std_abbr)
|
328 |
+
|
329 |
+
def __reduce__(self):
|
330 |
+
return (self.__class__, ())
|
331 |
+
|
332 |
+
|
333 |
+
def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
|
334 |
+
""" dayofweek == 0 means Sunday, whichweek 5 means last instance """
|
335 |
+
first = datetime.datetime(year, month, 1, hour, minute)
|
336 |
+
|
337 |
+
# This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),
|
338 |
+
# Because 7 % 7 = 0
|
339 |
+
weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1)
|
340 |
+
wd = weekdayone + ((whichweek - 1) * ONEWEEK)
|
341 |
+
if (wd.month != month):
|
342 |
+
wd -= ONEWEEK
|
343 |
+
|
344 |
+
return wd
|
345 |
+
|
346 |
+
|
347 |
+
def valuestodict(key):
|
348 |
+
"""Convert a registry key's values to a dictionary."""
|
349 |
+
dout = {}
|
350 |
+
size = winreg.QueryInfoKey(key)[1]
|
351 |
+
tz_res = None
|
352 |
+
|
353 |
+
for i in range(size):
|
354 |
+
key_name, value, dtype = winreg.EnumValue(key, i)
|
355 |
+
if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:
|
356 |
+
# If it's a DWORD (32-bit integer), it's stored as unsigned - convert
|
357 |
+
# that to a proper signed integer
|
358 |
+
if value & (1 << 31):
|
359 |
+
value = value - (1 << 32)
|
360 |
+
elif dtype == winreg.REG_SZ:
|
361 |
+
# If it's a reference to the tzres DLL, load the actual string
|
362 |
+
if value.startswith('@tzres'):
|
363 |
+
tz_res = tz_res or tzres()
|
364 |
+
value = tz_res.name_from_string(value)
|
365 |
+
|
366 |
+
value = value.rstrip('\x00') # Remove trailing nulls
|
367 |
+
|
368 |
+
dout[key_name] = value
|
369 |
+
|
370 |
+
return dout
|
venv/lib/python3.10/site-packages/dateutil/zoneinfo/__init__.py
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
import warnings
|
3 |
+
import json
|
4 |
+
|
5 |
+
from tarfile import TarFile
|
6 |
+
from pkgutil import get_data
|
7 |
+
from io import BytesIO
|
8 |
+
|
9 |
+
from dateutil.tz import tzfile as _tzfile
|
10 |
+
|
11 |
+
__all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"]
|
12 |
+
|
13 |
+
ZONEFILENAME = "dateutil-zoneinfo.tar.gz"
|
14 |
+
METADATA_FN = 'METADATA'
|
15 |
+
|
16 |
+
|
17 |
+
class tzfile(_tzfile):
|
18 |
+
def __reduce__(self):
|
19 |
+
return (gettz, (self._filename,))
|
20 |
+
|
21 |
+
|
22 |
+
def getzoneinfofile_stream():
|
23 |
+
try:
|
24 |
+
return BytesIO(get_data(__name__, ZONEFILENAME))
|
25 |
+
except IOError as e: # TODO switch to FileNotFoundError?
|
26 |
+
warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror))
|
27 |
+
return None
|
28 |
+
|
29 |
+
|
30 |
+
class ZoneInfoFile(object):
|
31 |
+
def __init__(self, zonefile_stream=None):
|
32 |
+
if zonefile_stream is not None:
|
33 |
+
with TarFile.open(fileobj=zonefile_stream) as tf:
|
34 |
+
self.zones = {zf.name: tzfile(tf.extractfile(zf), filename=zf.name)
|
35 |
+
for zf in tf.getmembers()
|
36 |
+
if zf.isfile() and zf.name != METADATA_FN}
|
37 |
+
# deal with links: They'll point to their parent object. Less
|
38 |
+
# waste of memory
|
39 |
+
links = {zl.name: self.zones[zl.linkname]
|
40 |
+
for zl in tf.getmembers() if
|
41 |
+
zl.islnk() or zl.issym()}
|
42 |
+
self.zones.update(links)
|
43 |
+
try:
|
44 |
+
metadata_json = tf.extractfile(tf.getmember(METADATA_FN))
|
45 |
+
metadata_str = metadata_json.read().decode('UTF-8')
|
46 |
+
self.metadata = json.loads(metadata_str)
|
47 |
+
except KeyError:
|
48 |
+
# no metadata in tar file
|
49 |
+
self.metadata = None
|
50 |
+
else:
|
51 |
+
self.zones = {}
|
52 |
+
self.metadata = None
|
53 |
+
|
54 |
+
def get(self, name, default=None):
|
55 |
+
"""
|
56 |
+
Wrapper for :func:`ZoneInfoFile.zones.get`. This is a convenience method
|
57 |
+
for retrieving zones from the zone dictionary.
|
58 |
+
|
59 |
+
:param name:
|
60 |
+
The name of the zone to retrieve. (Generally IANA zone names)
|
61 |
+
|
62 |
+
:param default:
|
63 |
+
The value to return in the event of a missing key.
|
64 |
+
|
65 |
+
.. versionadded:: 2.6.0
|
66 |
+
|
67 |
+
"""
|
68 |
+
return self.zones.get(name, default)
|
69 |
+
|
70 |
+
|
71 |
+
# The current API has gettz as a module function, although in fact it taps into
|
72 |
+
# a stateful class. So as a workaround for now, without changing the API, we
|
73 |
+
# will create a new "global" class instance the first time a user requests a
|
74 |
+
# timezone. Ugly, but adheres to the api.
|
75 |
+
#
|
76 |
+
# TODO: Remove after deprecation period.
|
77 |
+
_CLASS_ZONE_INSTANCE = []
|
78 |
+
|
79 |
+
|
80 |
+
def get_zonefile_instance(new_instance=False):
|
81 |
+
"""
|
82 |
+
This is a convenience function which provides a :class:`ZoneInfoFile`
|
83 |
+
instance using the data provided by the ``dateutil`` package. By default, it
|
84 |
+
caches a single instance of the ZoneInfoFile object and returns that.
|
85 |
+
|
86 |
+
:param new_instance:
|
87 |
+
If ``True``, a new instance of :class:`ZoneInfoFile` is instantiated and
|
88 |
+
used as the cached instance for the next call. Otherwise, new instances
|
89 |
+
are created only as necessary.
|
90 |
+
|
91 |
+
:return:
|
92 |
+
Returns a :class:`ZoneInfoFile` object.
|
93 |
+
|
94 |
+
.. versionadded:: 2.6
|
95 |
+
"""
|
96 |
+
if new_instance:
|
97 |
+
zif = None
|
98 |
+
else:
|
99 |
+
zif = getattr(get_zonefile_instance, '_cached_instance', None)
|
100 |
+
|
101 |
+
if zif is None:
|
102 |
+
zif = ZoneInfoFile(getzoneinfofile_stream())
|
103 |
+
|
104 |
+
get_zonefile_instance._cached_instance = zif
|
105 |
+
|
106 |
+
return zif
|
107 |
+
|
108 |
+
|
109 |
+
def gettz(name):
|
110 |
+
"""
|
111 |
+
This retrieves a time zone from the local zoneinfo tarball that is packaged
|
112 |
+
with dateutil.
|
113 |
+
|
114 |
+
:param name:
|
115 |
+
An IANA-style time zone name, as found in the zoneinfo file.
|
116 |
+
|
117 |
+
:return:
|
118 |
+
Returns a :class:`dateutil.tz.tzfile` time zone object.
|
119 |
+
|
120 |
+
.. warning::
|
121 |
+
It is generally inadvisable to use this function, and it is only
|
122 |
+
provided for API compatibility with earlier versions. This is *not*
|
123 |
+
equivalent to ``dateutil.tz.gettz()``, which selects an appropriate
|
124 |
+
time zone based on the inputs, favoring system zoneinfo. This is ONLY
|
125 |
+
for accessing the dateutil-specific zoneinfo (which may be out of
|
126 |
+
date compared to the system zoneinfo).
|
127 |
+
|
128 |
+
.. deprecated:: 2.6
|
129 |
+
If you need to use a specific zoneinfofile over the system zoneinfo,
|
130 |
+
instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call
|
131 |
+
:func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead.
|
132 |
+
|
133 |
+
Use :func:`get_zonefile_instance` to retrieve an instance of the
|
134 |
+
dateutil-provided zoneinfo.
|
135 |
+
"""
|
136 |
+
warnings.warn("zoneinfo.gettz() will be removed in future versions, "
|
137 |
+
"to use the dateutil-provided zoneinfo files, instantiate a "
|
138 |
+
"ZoneInfoFile object and use ZoneInfoFile.zones.get() "
|
139 |
+
"instead. See the documentation for details.",
|
140 |
+
DeprecationWarning)
|
141 |
+
|
142 |
+
if len(_CLASS_ZONE_INSTANCE) == 0:
|
143 |
+
_CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))
|
144 |
+
return _CLASS_ZONE_INSTANCE[0].zones.get(name)
|
145 |
+
|
146 |
+
|
147 |
+
def gettz_db_metadata():
|
148 |
+
""" Get the zonefile metadata
|
149 |
+
|
150 |
+
See `zonefile_metadata`_
|
151 |
+
|
152 |
+
:returns:
|
153 |
+
A dictionary with the database metadata
|
154 |
+
|
155 |
+
.. deprecated:: 2.6
|
156 |
+
See deprecation warning in :func:`zoneinfo.gettz`. To get metadata,
|
157 |
+
query the attribute ``zoneinfo.ZoneInfoFile.metadata``.
|
158 |
+
"""
|
159 |
+
warnings.warn("zoneinfo.gettz_db_metadata() will be removed in future "
|
160 |
+
"versions, to use the dateutil-provided zoneinfo files, "
|
161 |
+
"ZoneInfoFile object and query the 'metadata' attribute "
|
162 |
+
"instead. See the documentation for details.",
|
163 |
+
DeprecationWarning)
|
164 |
+
|
165 |
+
if len(_CLASS_ZONE_INSTANCE) == 0:
|
166 |
+
_CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))
|
167 |
+
return _CLASS_ZONE_INSTANCE[0].metadata
|
venv/lib/python3.10/site-packages/dateutil/zoneinfo/rebuild.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import os
|
3 |
+
import tempfile
|
4 |
+
import shutil
|
5 |
+
import json
|
6 |
+
from subprocess import check_call, check_output
|
7 |
+
from tarfile import TarFile
|
8 |
+
|
9 |
+
from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME
|
10 |
+
|
11 |
+
|
12 |
+
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
|
13 |
+
"""Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
|
14 |
+
|
15 |
+
filename is the timezone tarball from ``ftp.iana.org/tz``.
|
16 |
+
|
17 |
+
"""
|
18 |
+
tmpdir = tempfile.mkdtemp()
|
19 |
+
zonedir = os.path.join(tmpdir, "zoneinfo")
|
20 |
+
moduledir = os.path.dirname(__file__)
|
21 |
+
try:
|
22 |
+
with TarFile.open(filename) as tf:
|
23 |
+
for name in zonegroups:
|
24 |
+
tf.extract(name, tmpdir)
|
25 |
+
filepaths = [os.path.join(tmpdir, n) for n in zonegroups]
|
26 |
+
|
27 |
+
_run_zic(zonedir, filepaths)
|
28 |
+
|
29 |
+
# write metadata file
|
30 |
+
with open(os.path.join(zonedir, METADATA_FN), 'w') as f:
|
31 |
+
json.dump(metadata, f, indent=4, sort_keys=True)
|
32 |
+
target = os.path.join(moduledir, ZONEFILENAME)
|
33 |
+
with TarFile.open(target, "w:%s" % format) as tf:
|
34 |
+
for entry in os.listdir(zonedir):
|
35 |
+
entrypath = os.path.join(zonedir, entry)
|
36 |
+
tf.add(entrypath, entry)
|
37 |
+
finally:
|
38 |
+
shutil.rmtree(tmpdir)
|
39 |
+
|
40 |
+
|
41 |
+
def _run_zic(zonedir, filepaths):
|
42 |
+
"""Calls the ``zic`` compiler in a compatible way to get a "fat" binary.
|
43 |
+
|
44 |
+
Recent versions of ``zic`` default to ``-b slim``, while older versions
|
45 |
+
don't even have the ``-b`` option (but default to "fat" binaries). The
|
46 |
+
current version of dateutil does not support Version 2+ TZif files, which
|
47 |
+
causes problems when used in conjunction with "slim" binaries, so this
|
48 |
+
function is used to ensure that we always get a "fat" binary.
|
49 |
+
"""
|
50 |
+
|
51 |
+
try:
|
52 |
+
help_text = check_output(["zic", "--help"])
|
53 |
+
except OSError as e:
|
54 |
+
_print_on_nosuchfile(e)
|
55 |
+
raise
|
56 |
+
|
57 |
+
if b"-b " in help_text:
|
58 |
+
bloat_args = ["-b", "fat"]
|
59 |
+
else:
|
60 |
+
bloat_args = []
|
61 |
+
|
62 |
+
check_call(["zic"] + bloat_args + ["-d", zonedir] + filepaths)
|
63 |
+
|
64 |
+
|
65 |
+
def _print_on_nosuchfile(e):
|
66 |
+
"""Print helpful troubleshooting message
|
67 |
+
|
68 |
+
e is an exception raised by subprocess.check_call()
|
69 |
+
|
70 |
+
"""
|
71 |
+
if e.errno == 2:
|
72 |
+
logging.error(
|
73 |
+
"Could not find zic. Perhaps you need to install "
|
74 |
+
"libc-bin or some other package that provides it, "
|
75 |
+
"or it's not in your PATH?")
|
venv/lib/python3.10/site-packages/mpmath/__init__.py
ADDED
@@ -0,0 +1,468 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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3.0'
|
2 |
+
|
3 |
+
from .usertools import monitor, timing
|
4 |
+
|
5 |
+
from .ctx_fp import FPContext
|
6 |
+
from .ctx_mp import MPContext
|
7 |
+
from .ctx_iv import MPIntervalContext
|
8 |
+
|
9 |
+
fp = FPContext()
|
10 |
+
mp = MPContext()
|
11 |
+
iv = MPIntervalContext()
|
12 |
+
|
13 |
+
fp._mp = mp
|
14 |
+
mp._mp = mp
|
15 |
+
iv._mp = mp
|
16 |
+
mp._fp = fp
|
17 |
+
fp._fp = fp
|
18 |
+
mp._iv = iv
|
19 |
+
fp._iv = iv
|
20 |
+
iv._iv = iv
|
21 |
+
|
22 |
+
# XXX: extremely bad pickle hack
|
23 |
+
from . import ctx_mp as _ctx_mp
|
24 |
+
_ctx_mp._mpf_module.mpf = mp.mpf
|
25 |
+
_ctx_mp._mpf_module.mpc = mp.mpc
|
26 |
+
|
27 |
+
make_mpf = mp.make_mpf
|
28 |
+
make_mpc = mp.make_mpc
|
29 |
+
|
30 |
+
extraprec = mp.extraprec
|
31 |
+
extradps = mp.extradps
|
32 |
+
workprec = mp.workprec
|
33 |
+
workdps = mp.workdps
|
34 |
+
autoprec = mp.autoprec
|
35 |
+
maxcalls = mp.maxcalls
|
36 |
+
memoize = mp.memoize
|
37 |
+
|
38 |
+
mag = mp.mag
|
39 |
+
|
40 |
+
bernfrac = mp.bernfrac
|
41 |
+
|
42 |
+
qfrom = mp.qfrom
|
43 |
+
mfrom = mp.mfrom
|
44 |
+
kfrom = mp.kfrom
|
45 |
+
taufrom = mp.taufrom
|
46 |
+
qbarfrom = mp.qbarfrom
|
47 |
+
ellipfun = mp.ellipfun
|
48 |
+
jtheta = mp.jtheta
|
49 |
+
kleinj = mp.kleinj
|
50 |
+
eta = mp.eta
|
51 |
+
|
52 |
+
qp = mp.qp
|
53 |
+
qhyper = mp.qhyper
|
54 |
+
qgamma = mp.qgamma
|
55 |
+
qfac = mp.qfac
|
56 |
+
|
57 |
+
nint_distance = mp.nint_distance
|
58 |
+
|
59 |
+
plot = mp.plot
|
60 |
+
cplot = mp.cplot
|
61 |
+
splot = mp.splot
|
62 |
+
|
63 |
+
odefun = mp.odefun
|
64 |
+
|
65 |
+
jacobian = mp.jacobian
|
66 |
+
findroot = mp.findroot
|
67 |
+
multiplicity = mp.multiplicity
|
68 |
+
|
69 |
+
isinf = mp.isinf
|
70 |
+
isnan = mp.isnan
|
71 |
+
isnormal = mp.isnormal
|
72 |
+
isint = mp.isint
|
73 |
+
isfinite = mp.isfinite
|
74 |
+
almosteq = mp.almosteq
|
75 |
+
nan = mp.nan
|
76 |
+
rand = mp.rand
|
77 |
+
|
78 |
+
absmin = mp.absmin
|
79 |
+
absmax = mp.absmax
|
80 |
+
|
81 |
+
fraction = mp.fraction
|
82 |
+
|
83 |
+
linspace = mp.linspace
|
84 |
+
arange = mp.arange
|
85 |
+
|
86 |
+
mpmathify = convert = mp.convert
|
87 |
+
mpc = mp.mpc
|
88 |
+
|
89 |
+
mpi = iv._mpi
|
90 |
+
|
91 |
+
nstr = mp.nstr
|
92 |
+
nprint = mp.nprint
|
93 |
+
chop = mp.chop
|
94 |
+
|
95 |
+
fneg = mp.fneg
|
96 |
+
fadd = mp.fadd
|
97 |
+
fsub = mp.fsub
|
98 |
+
fmul = mp.fmul
|
99 |
+
fdiv = mp.fdiv
|
100 |
+
fprod = mp.fprod
|
101 |
+
|
102 |
+
quad = mp.quad
|
103 |
+
quadgl = mp.quadgl
|
104 |
+
quadts = mp.quadts
|
105 |
+
quadosc = mp.quadosc
|
106 |
+
quadsubdiv = mp.quadsubdiv
|
107 |
+
|
108 |
+
invertlaplace = mp.invertlaplace
|
109 |
+
invlaptalbot = mp.invlaptalbot
|
110 |
+
invlapstehfest = mp.invlapstehfest
|
111 |
+
invlapdehoog = mp.invlapdehoog
|
112 |
+
|
113 |
+
pslq = mp.pslq
|
114 |
+
identify = mp.identify
|
115 |
+
findpoly = mp.findpoly
|
116 |
+
|
117 |
+
richardson = mp.richardson
|
118 |
+
shanks = mp.shanks
|
119 |
+
levin = mp.levin
|
120 |
+
cohen_alt = mp.cohen_alt
|
121 |
+
nsum = mp.nsum
|
122 |
+
nprod = mp.nprod
|
123 |
+
difference = mp.difference
|
124 |
+
diff = mp.diff
|
125 |
+
diffs = mp.diffs
|
126 |
+
diffs_prod = mp.diffs_prod
|
127 |
+
diffs_exp = mp.diffs_exp
|
128 |
+
diffun = mp.diffun
|
129 |
+
differint = mp.differint
|
130 |
+
taylor = mp.taylor
|
131 |
+
pade = mp.pade
|
132 |
+
polyval = mp.polyval
|
133 |
+
polyroots = mp.polyroots
|
134 |
+
fourier = mp.fourier
|
135 |
+
fourierval = mp.fourierval
|
136 |
+
sumem = mp.sumem
|
137 |
+
sumap = mp.sumap
|
138 |
+
chebyfit = mp.chebyfit
|
139 |
+
limit = mp.limit
|
140 |
+
|
141 |
+
matrix = mp.matrix
|
142 |
+
eye = mp.eye
|
143 |
+
diag = mp.diag
|
144 |
+
zeros = mp.zeros
|
145 |
+
ones = mp.ones
|
146 |
+
hilbert = mp.hilbert
|
147 |
+
randmatrix = mp.randmatrix
|
148 |
+
swap_row = mp.swap_row
|
149 |
+
extend = mp.extend
|
150 |
+
norm = mp.norm
|
151 |
+
mnorm = mp.mnorm
|
152 |
+
|
153 |
+
lu_solve = mp.lu_solve
|
154 |
+
lu = mp.lu
|
155 |
+
qr = mp.qr
|
156 |
+
unitvector = mp.unitvector
|
157 |
+
inverse = mp.inverse
|
158 |
+
residual = mp.residual
|
159 |
+
qr_solve = mp.qr_solve
|
160 |
+
cholesky = mp.cholesky
|
161 |
+
cholesky_solve = mp.cholesky_solve
|
162 |
+
det = mp.det
|
163 |
+
cond = mp.cond
|
164 |
+
hessenberg = mp.hessenberg
|
165 |
+
schur = mp.schur
|
166 |
+
eig = mp.eig
|
167 |
+
eig_sort = mp.eig_sort
|
168 |
+
eigsy = mp.eigsy
|
169 |
+
eighe = mp.eighe
|
170 |
+
eigh = mp.eigh
|
171 |
+
svd_r = mp.svd_r
|
172 |
+
svd_c = mp.svd_c
|
173 |
+
svd = mp.svd
|
174 |
+
gauss_quadrature = mp.gauss_quadrature
|
175 |
+
|
176 |
+
expm = mp.expm
|
177 |
+
sqrtm = mp.sqrtm
|
178 |
+
powm = mp.powm
|
179 |
+
logm = mp.logm
|
180 |
+
sinm = mp.sinm
|
181 |
+
cosm = mp.cosm
|
182 |
+
|
183 |
+
mpf = mp.mpf
|
184 |
+
j = mp.j
|
185 |
+
exp = mp.exp
|
186 |
+
expj = mp.expj
|
187 |
+
expjpi = mp.expjpi
|
188 |
+
ln = mp.ln
|
189 |
+
im = mp.im
|
190 |
+
re = mp.re
|
191 |
+
inf = mp.inf
|
192 |
+
ninf = mp.ninf
|
193 |
+
sign = mp.sign
|
194 |
+
|
195 |
+
eps = mp.eps
|
196 |
+
pi = mp.pi
|
197 |
+
ln2 = mp.ln2
|
198 |
+
ln10 = mp.ln10
|
199 |
+
phi = mp.phi
|
200 |
+
e = mp.e
|
201 |
+
euler = mp.euler
|
202 |
+
catalan = mp.catalan
|
203 |
+
khinchin = mp.khinchin
|
204 |
+
glaisher = mp.glaisher
|
205 |
+
apery = mp.apery
|
206 |
+
degree = mp.degree
|
207 |
+
twinprime = mp.twinprime
|
208 |
+
mertens = mp.mertens
|
209 |
+
|
210 |
+
ldexp = mp.ldexp
|
211 |
+
frexp = mp.frexp
|
212 |
+
|
213 |
+
fsum = mp.fsum
|
214 |
+
fdot = mp.fdot
|
215 |
+
|
216 |
+
sqrt = mp.sqrt
|
217 |
+
cbrt = mp.cbrt
|
218 |
+
exp = mp.exp
|
219 |
+
ln = mp.ln
|
220 |
+
log = mp.log
|
221 |
+
log10 = mp.log10
|
222 |
+
power = mp.power
|
223 |
+
cos = mp.cos
|
224 |
+
sin = mp.sin
|
225 |
+
tan = mp.tan
|
226 |
+
cosh = mp.cosh
|
227 |
+
sinh = mp.sinh
|
228 |
+
tanh = mp.tanh
|
229 |
+
acos = mp.acos
|
230 |
+
asin = mp.asin
|
231 |
+
atan = mp.atan
|
232 |
+
asinh = mp.asinh
|
233 |
+
acosh = mp.acosh
|
234 |
+
atanh = mp.atanh
|
235 |
+
sec = mp.sec
|
236 |
+
csc = mp.csc
|
237 |
+
cot = mp.cot
|
238 |
+
sech = mp.sech
|
239 |
+
csch = mp.csch
|
240 |
+
coth = mp.coth
|
241 |
+
asec = mp.asec
|
242 |
+
acsc = mp.acsc
|
243 |
+
acot = mp.acot
|
244 |
+
asech = mp.asech
|
245 |
+
acsch = mp.acsch
|
246 |
+
acoth = mp.acoth
|
247 |
+
cospi = mp.cospi
|
248 |
+
sinpi = mp.sinpi
|
249 |
+
sinc = mp.sinc
|
250 |
+
sincpi = mp.sincpi
|
251 |
+
cos_sin = mp.cos_sin
|
252 |
+
cospi_sinpi = mp.cospi_sinpi
|
253 |
+
fabs = mp.fabs
|
254 |
+
re = mp.re
|
255 |
+
im = mp.im
|
256 |
+
conj = mp.conj
|
257 |
+
floor = mp.floor
|
258 |
+
ceil = mp.ceil
|
259 |
+
nint = mp.nint
|
260 |
+
frac = mp.frac
|
261 |
+
root = mp.root
|
262 |
+
nthroot = mp.nthroot
|
263 |
+
hypot = mp.hypot
|
264 |
+
fmod = mp.fmod
|
265 |
+
ldexp = mp.ldexp
|
266 |
+
frexp = mp.frexp
|
267 |
+
sign = mp.sign
|
268 |
+
arg = mp.arg
|
269 |
+
phase = mp.phase
|
270 |
+
polar = mp.polar
|
271 |
+
rect = mp.rect
|
272 |
+
degrees = mp.degrees
|
273 |
+
radians = mp.radians
|
274 |
+
atan2 = mp.atan2
|
275 |
+
fib = mp.fib
|
276 |
+
fibonacci = mp.fibonacci
|
277 |
+
lambertw = mp.lambertw
|
278 |
+
zeta = mp.zeta
|
279 |
+
altzeta = mp.altzeta
|
280 |
+
gamma = mp.gamma
|
281 |
+
rgamma = mp.rgamma
|
282 |
+
factorial = mp.factorial
|
283 |
+
fac = mp.fac
|
284 |
+
fac2 = mp.fac2
|
285 |
+
beta = mp.beta
|
286 |
+
betainc = mp.betainc
|
287 |
+
psi = mp.psi
|
288 |
+
#psi0 = mp.psi0
|
289 |
+
#psi1 = mp.psi1
|
290 |
+
#psi2 = mp.psi2
|
291 |
+
#psi3 = mp.psi3
|
292 |
+
polygamma = mp.polygamma
|
293 |
+
digamma = mp.digamma
|
294 |
+
#trigamma = mp.trigamma
|
295 |
+
#tetragamma = mp.tetragamma
|
296 |
+
#pentagamma = mp.pentagamma
|
297 |
+
harmonic = mp.harmonic
|
298 |
+
bernoulli = mp.bernoulli
|
299 |
+
bernfrac = mp.bernfrac
|
300 |
+
stieltjes = mp.stieltjes
|
301 |
+
hurwitz = mp.hurwitz
|
302 |
+
dirichlet = mp.dirichlet
|
303 |
+
bernpoly = mp.bernpoly
|
304 |
+
eulerpoly = mp.eulerpoly
|
305 |
+
eulernum = mp.eulernum
|
306 |
+
polylog = mp.polylog
|
307 |
+
clsin = mp.clsin
|
308 |
+
clcos = mp.clcos
|
309 |
+
gammainc = mp.gammainc
|
310 |
+
gammaprod = mp.gammaprod
|
311 |
+
binomial = mp.binomial
|
312 |
+
rf = mp.rf
|
313 |
+
ff = mp.ff
|
314 |
+
hyper = mp.hyper
|
315 |
+
hyp0f1 = mp.hyp0f1
|
316 |
+
hyp1f1 = mp.hyp1f1
|
317 |
+
hyp1f2 = mp.hyp1f2
|
318 |
+
hyp2f1 = mp.hyp2f1
|
319 |
+
hyp2f2 = mp.hyp2f2
|
320 |
+
hyp2f0 = mp.hyp2f0
|
321 |
+
hyp2f3 = mp.hyp2f3
|
322 |
+
hyp3f2 = mp.hyp3f2
|
323 |
+
hyperu = mp.hyperu
|
324 |
+
hypercomb = mp.hypercomb
|
325 |
+
meijerg = mp.meijerg
|
326 |
+
appellf1 = mp.appellf1
|
327 |
+
appellf2 = mp.appellf2
|
328 |
+
appellf3 = mp.appellf3
|
329 |
+
appellf4 = mp.appellf4
|
330 |
+
hyper2d = mp.hyper2d
|
331 |
+
bihyper = mp.bihyper
|
332 |
+
erf = mp.erf
|
333 |
+
erfc = mp.erfc
|
334 |
+
erfi = mp.erfi
|
335 |
+
erfinv = mp.erfinv
|
336 |
+
npdf = mp.npdf
|
337 |
+
ncdf = mp.ncdf
|
338 |
+
expint = mp.expint
|
339 |
+
e1 = mp.e1
|
340 |
+
ei = mp.ei
|
341 |
+
li = mp.li
|
342 |
+
ci = mp.ci
|
343 |
+
si = mp.si
|
344 |
+
chi = mp.chi
|
345 |
+
shi = mp.shi
|
346 |
+
fresnels = mp.fresnels
|
347 |
+
fresnelc = mp.fresnelc
|
348 |
+
airyai = mp.airyai
|
349 |
+
airybi = mp.airybi
|
350 |
+
airyaizero = mp.airyaizero
|
351 |
+
airybizero = mp.airybizero
|
352 |
+
scorergi = mp.scorergi
|
353 |
+
scorerhi = mp.scorerhi
|
354 |
+
ellipk = mp.ellipk
|
355 |
+
ellipe = mp.ellipe
|
356 |
+
ellipf = mp.ellipf
|
357 |
+
ellippi = mp.ellippi
|
358 |
+
elliprc = mp.elliprc
|
359 |
+
elliprj = mp.elliprj
|
360 |
+
elliprf = mp.elliprf
|
361 |
+
elliprd = mp.elliprd
|
362 |
+
elliprg = mp.elliprg
|
363 |
+
agm = mp.agm
|
364 |
+
jacobi = mp.jacobi
|
365 |
+
chebyt = mp.chebyt
|
366 |
+
chebyu = mp.chebyu
|
367 |
+
legendre = mp.legendre
|
368 |
+
legenp = mp.legenp
|
369 |
+
legenq = mp.legenq
|
370 |
+
hermite = mp.hermite
|
371 |
+
pcfd = mp.pcfd
|
372 |
+
pcfu = mp.pcfu
|
373 |
+
pcfv = mp.pcfv
|
374 |
+
pcfw = mp.pcfw
|
375 |
+
gegenbauer = mp.gegenbauer
|
376 |
+
laguerre = mp.laguerre
|
377 |
+
spherharm = mp.spherharm
|
378 |
+
besselj = mp.besselj
|
379 |
+
j0 = mp.j0
|
380 |
+
j1 = mp.j1
|
381 |
+
besseli = mp.besseli
|
382 |
+
bessely = mp.bessely
|
383 |
+
besselk = mp.besselk
|
384 |
+
besseljzero = mp.besseljzero
|
385 |
+
besselyzero = mp.besselyzero
|
386 |
+
hankel1 = mp.hankel1
|
387 |
+
hankel2 = mp.hankel2
|
388 |
+
struveh = mp.struveh
|
389 |
+
struvel = mp.struvel
|
390 |
+
angerj = mp.angerj
|
391 |
+
webere = mp.webere
|
392 |
+
lommels1 = mp.lommels1
|
393 |
+
lommels2 = mp.lommels2
|
394 |
+
whitm = mp.whitm
|
395 |
+
whitw = mp.whitw
|
396 |
+
ber = mp.ber
|
397 |
+
bei = mp.bei
|
398 |
+
ker = mp.ker
|
399 |
+
kei = mp.kei
|
400 |
+
coulombc = mp.coulombc
|
401 |
+
coulombf = mp.coulombf
|
402 |
+
coulombg = mp.coulombg
|
403 |
+
barnesg = mp.barnesg
|
404 |
+
superfac = mp.superfac
|
405 |
+
hyperfac = mp.hyperfac
|
406 |
+
loggamma = mp.loggamma
|
407 |
+
siegeltheta = mp.siegeltheta
|
408 |
+
siegelz = mp.siegelz
|
409 |
+
grampoint = mp.grampoint
|
410 |
+
zetazero = mp.zetazero
|
411 |
+
riemannr = mp.riemannr
|
412 |
+
primepi = mp.primepi
|
413 |
+
primepi2 = mp.primepi2
|
414 |
+
primezeta = mp.primezeta
|
415 |
+
bell = mp.bell
|
416 |
+
polyexp = mp.polyexp
|
417 |
+
expm1 = mp.expm1
|
418 |
+
log1p = mp.log1p
|
419 |
+
powm1 = mp.powm1
|
420 |
+
unitroots = mp.unitroots
|
421 |
+
cyclotomic = mp.cyclotomic
|
422 |
+
mangoldt = mp.mangoldt
|
423 |
+
secondzeta = mp.secondzeta
|
424 |
+
nzeros = mp.nzeros
|
425 |
+
backlunds = mp.backlunds
|
426 |
+
lerchphi = mp.lerchphi
|
427 |
+
stirling1 = mp.stirling1
|
428 |
+
stirling2 = mp.stirling2
|
429 |
+
squarew = mp.squarew
|
430 |
+
trianglew = mp.trianglew
|
431 |
+
sawtoothw = mp.sawtoothw
|
432 |
+
unit_triangle = mp.unit_triangle
|
433 |
+
sigmoid = mp.sigmoid
|
434 |
+
|
435 |
+
# be careful when changing this name, don't use test*!
|
436 |
+
def runtests():
|
437 |
+
"""
|
438 |
+
Run all mpmath tests and print output.
|
439 |
+
"""
|
440 |
+
import os.path
|
441 |
+
from inspect import getsourcefile
|
442 |
+
from .tests import runtests as tests
|
443 |
+
testdir = os.path.dirname(os.path.abspath(getsourcefile(tests)))
|
444 |
+
importdir = os.path.abspath(testdir + '/../..')
|
445 |
+
tests.testit(importdir, testdir)
|
446 |
+
|
447 |
+
def doctests(filter=[]):
|
448 |
+
import sys
|
449 |
+
from timeit import default_timer as clock
|
450 |
+
for i, arg in enumerate(sys.argv):
|
451 |
+
if '__init__.py' in arg:
|
452 |
+
filter = [sn for sn in sys.argv[i+1:] if not sn.startswith("-")]
|
453 |
+
break
|
454 |
+
import doctest
|
455 |
+
globs = globals().copy()
|
456 |
+
for obj in globs: #sorted(globs.keys()):
|
457 |
+
if filter:
|
458 |
+
if not sum([pat in obj for pat in filter]):
|
459 |
+
continue
|
460 |
+
sys.stdout.write(str(obj) + " ")
|
461 |
+
sys.stdout.flush()
|
462 |
+
t1 = clock()
|
463 |
+
doctest.run_docstring_examples(globs[obj], {}, verbose=("-v" in sys.argv))
|
464 |
+
t2 = clock()
|
465 |
+
print(round(t2-t1, 3))
|
466 |
+
|
467 |
+
if __name__ == '__main__':
|
468 |
+
doctests()
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (8.28 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_base.cpython-310.pyc
ADDED
Binary file (16.3 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_fp.cpython-310.pyc
ADDED
Binary file (7.83 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_iv.cpython-310.pyc
ADDED
Binary file (20.5 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp.cpython-310.pyc
ADDED
Binary file (43 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp_python.cpython-310.pyc
ADDED
Binary file (34.6 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/function_docs.cpython-310.pyc
ADDED
Binary file (284 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/identification.cpython-310.pyc
ADDED
Binary file (28.3 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/math2.cpython-310.pyc
ADDED
Binary file (15.1 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/rational.cpython-310.pyc
ADDED
Binary file (5.97 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/usertools.cpython-310.pyc
ADDED
Binary file (3.61 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/__pycache__/visualization.cpython-310.pyc
ADDED
Binary file (9.71 kB). View file
|
|
venv/lib/python3.10/site-packages/mpmath/ctx_base.py
ADDED
@@ -0,0 +1,494 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from operator import gt, lt
|
2 |
+
|
3 |
+
from .libmp.backend import xrange
|
4 |
+
|
5 |
+
from .functions.functions import SpecialFunctions
|
6 |
+
from .functions.rszeta import RSCache
|
7 |
+
from .calculus.quadrature import QuadratureMethods
|
8 |
+
from .calculus.inverselaplace import LaplaceTransformInversionMethods
|
9 |
+
from .calculus.calculus import CalculusMethods
|
10 |
+
from .calculus.optimization import OptimizationMethods
|
11 |
+
from .calculus.odes import ODEMethods
|
12 |
+
from .matrices.matrices import MatrixMethods
|
13 |
+
from .matrices.calculus import MatrixCalculusMethods
|
14 |
+
from .matrices.linalg import LinearAlgebraMethods
|
15 |
+
from .matrices.eigen import Eigen
|
16 |
+
from .identification import IdentificationMethods
|
17 |
+
from .visualization import VisualizationMethods
|
18 |
+
|
19 |
+
from . import libmp
|
20 |
+
|
21 |
+
class Context(object):
|
22 |
+
pass
|
23 |
+
|
24 |
+
class StandardBaseContext(Context,
|
25 |
+
SpecialFunctions,
|
26 |
+
RSCache,
|
27 |
+
QuadratureMethods,
|
28 |
+
LaplaceTransformInversionMethods,
|
29 |
+
CalculusMethods,
|
30 |
+
MatrixMethods,
|
31 |
+
MatrixCalculusMethods,
|
32 |
+
LinearAlgebraMethods,
|
33 |
+
Eigen,
|
34 |
+
IdentificationMethods,
|
35 |
+
OptimizationMethods,
|
36 |
+
ODEMethods,
|
37 |
+
VisualizationMethods):
|
38 |
+
|
39 |
+
NoConvergence = libmp.NoConvergence
|
40 |
+
ComplexResult = libmp.ComplexResult
|
41 |
+
|
42 |
+
def __init__(ctx):
|
43 |
+
ctx._aliases = {}
|
44 |
+
# Call those that need preinitialization (e.g. for wrappers)
|
45 |
+
SpecialFunctions.__init__(ctx)
|
46 |
+
RSCache.__init__(ctx)
|
47 |
+
QuadratureMethods.__init__(ctx)
|
48 |
+
LaplaceTransformInversionMethods.__init__(ctx)
|
49 |
+
CalculusMethods.__init__(ctx)
|
50 |
+
MatrixMethods.__init__(ctx)
|
51 |
+
|
52 |
+
def _init_aliases(ctx):
|
53 |
+
for alias, value in ctx._aliases.items():
|
54 |
+
try:
|
55 |
+
setattr(ctx, alias, getattr(ctx, value))
|
56 |
+
except AttributeError:
|
57 |
+
pass
|
58 |
+
|
59 |
+
_fixed_precision = False
|
60 |
+
|
61 |
+
# XXX
|
62 |
+
verbose = False
|
63 |
+
|
64 |
+
def warn(ctx, msg):
|
65 |
+
print("Warning:", msg)
|
66 |
+
|
67 |
+
def bad_domain(ctx, msg):
|
68 |
+
raise ValueError(msg)
|
69 |
+
|
70 |
+
def _re(ctx, x):
|
71 |
+
if hasattr(x, "real"):
|
72 |
+
return x.real
|
73 |
+
return x
|
74 |
+
|
75 |
+
def _im(ctx, x):
|
76 |
+
if hasattr(x, "imag"):
|
77 |
+
return x.imag
|
78 |
+
return ctx.zero
|
79 |
+
|
80 |
+
def _as_points(ctx, x):
|
81 |
+
return x
|
82 |
+
|
83 |
+
def fneg(ctx, x, **kwargs):
|
84 |
+
return -ctx.convert(x)
|
85 |
+
|
86 |
+
def fadd(ctx, x, y, **kwargs):
|
87 |
+
return ctx.convert(x)+ctx.convert(y)
|
88 |
+
|
89 |
+
def fsub(ctx, x, y, **kwargs):
|
90 |
+
return ctx.convert(x)-ctx.convert(y)
|
91 |
+
|
92 |
+
def fmul(ctx, x, y, **kwargs):
|
93 |
+
return ctx.convert(x)*ctx.convert(y)
|
94 |
+
|
95 |
+
def fdiv(ctx, x, y, **kwargs):
|
96 |
+
return ctx.convert(x)/ctx.convert(y)
|
97 |
+
|
98 |
+
def fsum(ctx, args, absolute=False, squared=False):
|
99 |
+
if absolute:
|
100 |
+
if squared:
|
101 |
+
return sum((abs(x)**2 for x in args), ctx.zero)
|
102 |
+
return sum((abs(x) for x in args), ctx.zero)
|
103 |
+
if squared:
|
104 |
+
return sum((x**2 for x in args), ctx.zero)
|
105 |
+
return sum(args, ctx.zero)
|
106 |
+
|
107 |
+
def fdot(ctx, xs, ys=None, conjugate=False):
|
108 |
+
if ys is not None:
|
109 |
+
xs = zip(xs, ys)
|
110 |
+
if conjugate:
|
111 |
+
cf = ctx.conj
|
112 |
+
return sum((x*cf(y) for (x,y) in xs), ctx.zero)
|
113 |
+
else:
|
114 |
+
return sum((x*y for (x,y) in xs), ctx.zero)
|
115 |
+
|
116 |
+
def fprod(ctx, args):
|
117 |
+
prod = ctx.one
|
118 |
+
for arg in args:
|
119 |
+
prod *= arg
|
120 |
+
return prod
|
121 |
+
|
122 |
+
def nprint(ctx, x, n=6, **kwargs):
|
123 |
+
"""
|
124 |
+
Equivalent to ``print(nstr(x, n))``.
|
125 |
+
"""
|
126 |
+
print(ctx.nstr(x, n, **kwargs))
|
127 |
+
|
128 |
+
def chop(ctx, x, tol=None):
|
129 |
+
"""
|
130 |
+
Chops off small real or imaginary parts, or converts
|
131 |
+
numbers close to zero to exact zeros. The input can be a
|
132 |
+
single number or an iterable::
|
133 |
+
|
134 |
+
>>> from mpmath import *
|
135 |
+
>>> mp.dps = 15; mp.pretty = False
|
136 |
+
>>> chop(5+1e-10j, tol=1e-9)
|
137 |
+
mpf('5.0')
|
138 |
+
>>> nprint(chop([1.0, 1e-20, 3+1e-18j, -4, 2]))
|
139 |
+
[1.0, 0.0, 3.0, -4.0, 2.0]
|
140 |
+
|
141 |
+
The tolerance defaults to ``100*eps``.
|
142 |
+
"""
|
143 |
+
if tol is None:
|
144 |
+
tol = 100*ctx.eps
|
145 |
+
try:
|
146 |
+
x = ctx.convert(x)
|
147 |
+
absx = abs(x)
|
148 |
+
if abs(x) < tol:
|
149 |
+
return ctx.zero
|
150 |
+
if ctx._is_complex_type(x):
|
151 |
+
#part_tol = min(tol, absx*tol)
|
152 |
+
part_tol = max(tol, absx*tol)
|
153 |
+
if abs(x.imag) < part_tol:
|
154 |
+
return x.real
|
155 |
+
if abs(x.real) < part_tol:
|
156 |
+
return ctx.mpc(0, x.imag)
|
157 |
+
except TypeError:
|
158 |
+
if isinstance(x, ctx.matrix):
|
159 |
+
return x.apply(lambda a: ctx.chop(a, tol))
|
160 |
+
if hasattr(x, "__iter__"):
|
161 |
+
return [ctx.chop(a, tol) for a in x]
|
162 |
+
return x
|
163 |
+
|
164 |
+
def almosteq(ctx, s, t, rel_eps=None, abs_eps=None):
|
165 |
+
r"""
|
166 |
+
Determine whether the difference between `s` and `t` is smaller
|
167 |
+
than a given epsilon, either relatively or absolutely.
|
168 |
+
|
169 |
+
Both a maximum relative difference and a maximum difference
|
170 |
+
('epsilons') may be specified. The absolute difference is
|
171 |
+
defined as `|s-t|` and the relative difference is defined
|
172 |
+
as `|s-t|/\max(|s|, |t|)`.
|
173 |
+
|
174 |
+
If only one epsilon is given, both are set to the same value.
|
175 |
+
If none is given, both epsilons are set to `2^{-p+m}` where
|
176 |
+
`p` is the current working precision and `m` is a small
|
177 |
+
integer. The default setting typically allows :func:`~mpmath.almosteq`
|
178 |
+
to be used to check for mathematical equality
|
179 |
+
in the presence of small rounding errors.
|
180 |
+
|
181 |
+
**Examples**
|
182 |
+
|
183 |
+
>>> from mpmath import *
|
184 |
+
>>> mp.dps = 15
|
185 |
+
>>> almosteq(3.141592653589793, 3.141592653589790)
|
186 |
+
True
|
187 |
+
>>> almosteq(3.141592653589793, 3.141592653589700)
|
188 |
+
False
|
189 |
+
>>> almosteq(3.141592653589793, 3.141592653589700, 1e-10)
|
190 |
+
True
|
191 |
+
>>> almosteq(1e-20, 2e-20)
|
192 |
+
True
|
193 |
+
>>> almosteq(1e-20, 2e-20, rel_eps=0, abs_eps=0)
|
194 |
+
False
|
195 |
+
|
196 |
+
"""
|
197 |
+
t = ctx.convert(t)
|
198 |
+
if abs_eps is None and rel_eps is None:
|
199 |
+
rel_eps = abs_eps = ctx.ldexp(1, -ctx.prec+4)
|
200 |
+
if abs_eps is None:
|
201 |
+
abs_eps = rel_eps
|
202 |
+
elif rel_eps is None:
|
203 |
+
rel_eps = abs_eps
|
204 |
+
diff = abs(s-t)
|
205 |
+
if diff <= abs_eps:
|
206 |
+
return True
|
207 |
+
abss = abs(s)
|
208 |
+
abst = abs(t)
|
209 |
+
if abss < abst:
|
210 |
+
err = diff/abst
|
211 |
+
else:
|
212 |
+
err = diff/abss
|
213 |
+
return err <= rel_eps
|
214 |
+
|
215 |
+
def arange(ctx, *args):
|
216 |
+
r"""
|
217 |
+
This is a generalized version of Python's :func:`~mpmath.range` function
|
218 |
+
that accepts fractional endpoints and step sizes and
|
219 |
+
returns a list of ``mpf`` instances. Like :func:`~mpmath.range`,
|
220 |
+
:func:`~mpmath.arange` can be called with 1, 2 or 3 arguments:
|
221 |
+
|
222 |
+
``arange(b)``
|
223 |
+
`[0, 1, 2, \ldots, x]`
|
224 |
+
``arange(a, b)``
|
225 |
+
`[a, a+1, a+2, \ldots, x]`
|
226 |
+
``arange(a, b, h)``
|
227 |
+
`[a, a+h, a+h, \ldots, x]`
|
228 |
+
|
229 |
+
where `b-1 \le x < b` (in the third case, `b-h \le x < b`).
|
230 |
+
|
231 |
+
Like Python's :func:`~mpmath.range`, the endpoint is not included. To
|
232 |
+
produce ranges where the endpoint is included, :func:`~mpmath.linspace`
|
233 |
+
is more convenient.
|
234 |
+
|
235 |
+
**Examples**
|
236 |
+
|
237 |
+
>>> from mpmath import *
|
238 |
+
>>> mp.dps = 15; mp.pretty = False
|
239 |
+
>>> arange(4)
|
240 |
+
[mpf('0.0'), mpf('1.0'), mpf('2.0'), mpf('3.0')]
|
241 |
+
>>> arange(1, 2, 0.25)
|
242 |
+
[mpf('1.0'), mpf('1.25'), mpf('1.5'), mpf('1.75')]
|
243 |
+
>>> arange(1, -1, -0.75)
|
244 |
+
[mpf('1.0'), mpf('0.25'), mpf('-0.5')]
|
245 |
+
|
246 |
+
"""
|
247 |
+
if not len(args) <= 3:
|
248 |
+
raise TypeError('arange expected at most 3 arguments, got %i'
|
249 |
+
% len(args))
|
250 |
+
if not len(args) >= 1:
|
251 |
+
raise TypeError('arange expected at least 1 argument, got %i'
|
252 |
+
% len(args))
|
253 |
+
# set default
|
254 |
+
a = 0
|
255 |
+
dt = 1
|
256 |
+
# interpret arguments
|
257 |
+
if len(args) == 1:
|
258 |
+
b = args[0]
|
259 |
+
elif len(args) >= 2:
|
260 |
+
a = args[0]
|
261 |
+
b = args[1]
|
262 |
+
if len(args) == 3:
|
263 |
+
dt = args[2]
|
264 |
+
a, b, dt = ctx.mpf(a), ctx.mpf(b), ctx.mpf(dt)
|
265 |
+
assert a + dt != a, 'dt is too small and would cause an infinite loop'
|
266 |
+
# adapt code for sign of dt
|
267 |
+
if a > b:
|
268 |
+
if dt > 0:
|
269 |
+
return []
|
270 |
+
op = gt
|
271 |
+
else:
|
272 |
+
if dt < 0:
|
273 |
+
return []
|
274 |
+
op = lt
|
275 |
+
# create list
|
276 |
+
result = []
|
277 |
+
i = 0
|
278 |
+
t = a
|
279 |
+
while 1:
|
280 |
+
t = a + dt*i
|
281 |
+
i += 1
|
282 |
+
if op(t, b):
|
283 |
+
result.append(t)
|
284 |
+
else:
|
285 |
+
break
|
286 |
+
return result
|
287 |
+
|
288 |
+
def linspace(ctx, *args, **kwargs):
|
289 |
+
"""
|
290 |
+
``linspace(a, b, n)`` returns a list of `n` evenly spaced
|
291 |
+
samples from `a` to `b`. The syntax ``linspace(mpi(a,b), n)``
|
292 |
+
is also valid.
|
293 |
+
|
294 |
+
This function is often more convenient than :func:`~mpmath.arange`
|
295 |
+
for partitioning an interval into subintervals, since
|
296 |
+
the endpoint is included::
|
297 |
+
|
298 |
+
>>> from mpmath import *
|
299 |
+
>>> mp.dps = 15; mp.pretty = False
|
300 |
+
>>> linspace(1, 4, 4)
|
301 |
+
[mpf('1.0'), mpf('2.0'), mpf('3.0'), mpf('4.0')]
|
302 |
+
|
303 |
+
You may also provide the keyword argument ``endpoint=False``::
|
304 |
+
|
305 |
+
>>> linspace(1, 4, 4, endpoint=False)
|
306 |
+
[mpf('1.0'), mpf('1.75'), mpf('2.5'), mpf('3.25')]
|
307 |
+
|
308 |
+
"""
|
309 |
+
if len(args) == 3:
|
310 |
+
a = ctx.mpf(args[0])
|
311 |
+
b = ctx.mpf(args[1])
|
312 |
+
n = int(args[2])
|
313 |
+
elif len(args) == 2:
|
314 |
+
assert hasattr(args[0], '_mpi_')
|
315 |
+
a = args[0].a
|
316 |
+
b = args[0].b
|
317 |
+
n = int(args[1])
|
318 |
+
else:
|
319 |
+
raise TypeError('linspace expected 2 or 3 arguments, got %i' \
|
320 |
+
% len(args))
|
321 |
+
if n < 1:
|
322 |
+
raise ValueError('n must be greater than 0')
|
323 |
+
if not 'endpoint' in kwargs or kwargs['endpoint']:
|
324 |
+
if n == 1:
|
325 |
+
return [ctx.mpf(a)]
|
326 |
+
step = (b - a) / ctx.mpf(n - 1)
|
327 |
+
y = [i*step + a for i in xrange(n)]
|
328 |
+
y[-1] = b
|
329 |
+
else:
|
330 |
+
step = (b - a) / ctx.mpf(n)
|
331 |
+
y = [i*step + a for i in xrange(n)]
|
332 |
+
return y
|
333 |
+
|
334 |
+
def cos_sin(ctx, z, **kwargs):
|
335 |
+
return ctx.cos(z, **kwargs), ctx.sin(z, **kwargs)
|
336 |
+
|
337 |
+
def cospi_sinpi(ctx, z, **kwargs):
|
338 |
+
return ctx.cospi(z, **kwargs), ctx.sinpi(z, **kwargs)
|
339 |
+
|
340 |
+
def _default_hyper_maxprec(ctx, p):
|
341 |
+
return int(1000 * p**0.25 + 4*p)
|
342 |
+
|
343 |
+
_gcd = staticmethod(libmp.gcd)
|
344 |
+
list_primes = staticmethod(libmp.list_primes)
|
345 |
+
isprime = staticmethod(libmp.isprime)
|
346 |
+
bernfrac = staticmethod(libmp.bernfrac)
|
347 |
+
moebius = staticmethod(libmp.moebius)
|
348 |
+
_ifac = staticmethod(libmp.ifac)
|
349 |
+
_eulernum = staticmethod(libmp.eulernum)
|
350 |
+
_stirling1 = staticmethod(libmp.stirling1)
|
351 |
+
_stirling2 = staticmethod(libmp.stirling2)
|
352 |
+
|
353 |
+
def sum_accurately(ctx, terms, check_step=1):
|
354 |
+
prec = ctx.prec
|
355 |
+
try:
|
356 |
+
extraprec = 10
|
357 |
+
while 1:
|
358 |
+
ctx.prec = prec + extraprec + 5
|
359 |
+
max_mag = ctx.ninf
|
360 |
+
s = ctx.zero
|
361 |
+
k = 0
|
362 |
+
for term in terms():
|
363 |
+
s += term
|
364 |
+
if (not k % check_step) and term:
|
365 |
+
term_mag = ctx.mag(term)
|
366 |
+
max_mag = max(max_mag, term_mag)
|
367 |
+
sum_mag = ctx.mag(s)
|
368 |
+
if sum_mag - term_mag > ctx.prec:
|
369 |
+
break
|
370 |
+
k += 1
|
371 |
+
cancellation = max_mag - sum_mag
|
372 |
+
if cancellation != cancellation:
|
373 |
+
break
|
374 |
+
if cancellation < extraprec or ctx._fixed_precision:
|
375 |
+
break
|
376 |
+
extraprec += min(ctx.prec, cancellation)
|
377 |
+
return s
|
378 |
+
finally:
|
379 |
+
ctx.prec = prec
|
380 |
+
|
381 |
+
def mul_accurately(ctx, factors, check_step=1):
|
382 |
+
prec = ctx.prec
|
383 |
+
try:
|
384 |
+
extraprec = 10
|
385 |
+
while 1:
|
386 |
+
ctx.prec = prec + extraprec + 5
|
387 |
+
max_mag = ctx.ninf
|
388 |
+
one = ctx.one
|
389 |
+
s = one
|
390 |
+
k = 0
|
391 |
+
for factor in factors():
|
392 |
+
s *= factor
|
393 |
+
term = factor - one
|
394 |
+
if (not k % check_step):
|
395 |
+
term_mag = ctx.mag(term)
|
396 |
+
max_mag = max(max_mag, term_mag)
|
397 |
+
sum_mag = ctx.mag(s-one)
|
398 |
+
#if sum_mag - term_mag > ctx.prec:
|
399 |
+
# break
|
400 |
+
if -term_mag > ctx.prec:
|
401 |
+
break
|
402 |
+
k += 1
|
403 |
+
cancellation = max_mag - sum_mag
|
404 |
+
if cancellation != cancellation:
|
405 |
+
break
|
406 |
+
if cancellation < extraprec or ctx._fixed_precision:
|
407 |
+
break
|
408 |
+
extraprec += min(ctx.prec, cancellation)
|
409 |
+
return s
|
410 |
+
finally:
|
411 |
+
ctx.prec = prec
|
412 |
+
|
413 |
+
def power(ctx, x, y):
|
414 |
+
r"""Converts `x` and `y` to mpmath numbers and evaluates
|
415 |
+
`x^y = \exp(y \log(x))`::
|
416 |
+
|
417 |
+
>>> from mpmath import *
|
418 |
+
>>> mp.dps = 30; mp.pretty = True
|
419 |
+
>>> power(2, 0.5)
|
420 |
+
1.41421356237309504880168872421
|
421 |
+
|
422 |
+
This shows the leading few digits of a large Mersenne prime
|
423 |
+
(performing the exact calculation ``2**43112609-1`` and
|
424 |
+
displaying the result in Python would be very slow)::
|
425 |
+
|
426 |
+
>>> power(2, 43112609)-1
|
427 |
+
3.16470269330255923143453723949e+12978188
|
428 |
+
"""
|
429 |
+
return ctx.convert(x) ** ctx.convert(y)
|
430 |
+
|
431 |
+
def _zeta_int(ctx, n):
|
432 |
+
return ctx.zeta(n)
|
433 |
+
|
434 |
+
def maxcalls(ctx, f, N):
|
435 |
+
"""
|
436 |
+
Return a wrapped copy of *f* that raises ``NoConvergence`` when *f*
|
437 |
+
has been called more than *N* times::
|
438 |
+
|
439 |
+
>>> from mpmath import *
|
440 |
+
>>> mp.dps = 15
|
441 |
+
>>> f = maxcalls(sin, 10)
|
442 |
+
>>> print(sum(f(n) for n in range(10)))
|
443 |
+
1.95520948210738
|
444 |
+
>>> f(10) # doctest: +IGNORE_EXCEPTION_DETAIL
|
445 |
+
Traceback (most recent call last):
|
446 |
+
...
|
447 |
+
NoConvergence: maxcalls: function evaluated 10 times
|
448 |
+
|
449 |
+
"""
|
450 |
+
counter = [0]
|
451 |
+
def f_maxcalls_wrapped(*args, **kwargs):
|
452 |
+
counter[0] += 1
|
453 |
+
if counter[0] > N:
|
454 |
+
raise ctx.NoConvergence("maxcalls: function evaluated %i times" % N)
|
455 |
+
return f(*args, **kwargs)
|
456 |
+
return f_maxcalls_wrapped
|
457 |
+
|
458 |
+
def memoize(ctx, f):
|
459 |
+
"""
|
460 |
+
Return a wrapped copy of *f* that caches computed values, i.e.
|
461 |
+
a memoized copy of *f*. Values are only reused if the cached precision
|
462 |
+
is equal to or higher than the working precision::
|
463 |
+
|
464 |
+
>>> from mpmath import *
|
465 |
+
>>> mp.dps = 15; mp.pretty = True
|
466 |
+
>>> f = memoize(maxcalls(sin, 1))
|
467 |
+
>>> f(2)
|
468 |
+
0.909297426825682
|
469 |
+
>>> f(2)
|
470 |
+
0.909297426825682
|
471 |
+
>>> mp.dps = 25
|
472 |
+
>>> f(2) # doctest: +IGNORE_EXCEPTION_DETAIL
|
473 |
+
Traceback (most recent call last):
|
474 |
+
...
|
475 |
+
NoConvergence: maxcalls: function evaluated 1 times
|
476 |
+
|
477 |
+
"""
|
478 |
+
f_cache = {}
|
479 |
+
def f_cached(*args, **kwargs):
|
480 |
+
if kwargs:
|
481 |
+
key = args, tuple(kwargs.items())
|
482 |
+
else:
|
483 |
+
key = args
|
484 |
+
prec = ctx.prec
|
485 |
+
if key in f_cache:
|
486 |
+
cprec, cvalue = f_cache[key]
|
487 |
+
if cprec >= prec:
|
488 |
+
return +cvalue
|
489 |
+
value = f(*args, **kwargs)
|
490 |
+
f_cache[key] = (prec, value)
|
491 |
+
return value
|
492 |
+
f_cached.__name__ = f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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .ctx_base import StandardBaseContext
|
2 |
+
|
3 |
+
import math
|
4 |
+
import cmath
|
5 |
+
from . import math2
|
6 |
+
|
7 |
+
from . import function_docs
|
8 |
+
|
9 |
+
from .libmp import mpf_bernoulli, to_float, int_types
|
10 |
+
from . import libmp
|
11 |
+
|
12 |
+
class FPContext(StandardBaseContext):
|
13 |
+
"""
|
14 |
+
Context for fast low-precision arithmetic (53-bit precision, giving at most
|
15 |
+
about 15-digit accuracy), using Python's builtin float and complex.
|
16 |
+
"""
|
17 |
+
|
18 |
+
def __init__(ctx):
|
19 |
+
StandardBaseContext.__init__(ctx)
|
20 |
+
|
21 |
+
# Override SpecialFunctions implementation
|
22 |
+
ctx.loggamma = math2.loggamma
|
23 |
+
ctx._bernoulli_cache = {}
|
24 |
+
ctx.pretty = False
|
25 |
+
|
26 |
+
ctx._init_aliases()
|
27 |
+
|
28 |
+
_mpq = lambda cls, x: float(x[0])/x[1]
|
29 |
+
|
30 |
+
NoConvergence = libmp.NoConvergence
|
31 |
+
|
32 |
+
def _get_prec(ctx): return 53
|
33 |
+
def _set_prec(ctx, p): return
|
34 |
+
def _get_dps(ctx): return 15
|
35 |
+
def _set_dps(ctx, p): return
|
36 |
+
|
37 |
+
_fixed_precision = True
|
38 |
+
|
39 |
+
prec = property(_get_prec, _set_prec)
|
40 |
+
dps = property(_get_dps, _set_dps)
|
41 |
+
|
42 |
+
zero = 0.0
|
43 |
+
one = 1.0
|
44 |
+
eps = math2.EPS
|
45 |
+
inf = math2.INF
|
46 |
+
ninf = math2.NINF
|
47 |
+
nan = math2.NAN
|
48 |
+
j = 1j
|
49 |
+
|
50 |
+
# Called by SpecialFunctions.__init__()
|
51 |
+
@classmethod
|
52 |
+
def _wrap_specfun(cls, name, f, wrap):
|
53 |
+
if wrap:
|
54 |
+
def f_wrapped(ctx, *args, **kwargs):
|
55 |
+
convert = ctx.convert
|
56 |
+
args = [convert(a) for a in args]
|
57 |
+
return f(ctx, *args, **kwargs)
|
58 |
+
else:
|
59 |
+
f_wrapped = f
|
60 |
+
f_wrapped.__doc__ = function_docs.__dict__.get(name, f.__doc__)
|
61 |
+
setattr(cls, name, f_wrapped)
|
62 |
+
|
63 |
+
def bernoulli(ctx, n):
|
64 |
+
cache = ctx._bernoulli_cache
|
65 |
+
if n in cache:
|
66 |
+
return cache[n]
|
67 |
+
cache[n] = to_float(mpf_bernoulli(n, 53, 'n'), strict=True)
|
68 |
+
return cache[n]
|
69 |
+
|
70 |
+
pi = math2.pi
|
71 |
+
e = math2.e
|
72 |
+
euler = math2.euler
|
73 |
+
sqrt2 = 1.4142135623730950488
|
74 |
+
sqrt5 = 2.2360679774997896964
|
75 |
+
phi = 1.6180339887498948482
|
76 |
+
ln2 = 0.69314718055994530942
|
77 |
+
ln10 = 2.302585092994045684
|
78 |
+
euler = 0.57721566490153286061
|
79 |
+
catalan = 0.91596559417721901505
|
80 |
+
khinchin = 2.6854520010653064453
|
81 |
+
apery = 1.2020569031595942854
|
82 |
+
glaisher = 1.2824271291006226369
|
83 |
+
|
84 |
+
absmin = absmax = abs
|
85 |
+
|
86 |
+
def is_special(ctx, x):
|
87 |
+
return x - x != 0.0
|
88 |
+
|
89 |
+
def isnan(ctx, x):
|
90 |
+
return x != x
|
91 |
+
|
92 |
+
def isinf(ctx, x):
|
93 |
+
return abs(x) == math2.INF
|
94 |
+
|
95 |
+
def isnormal(ctx, x):
|
96 |
+
if x:
|
97 |
+
return x - x == 0.0
|
98 |
+
return False
|
99 |
+
|
100 |
+
def isnpint(ctx, x):
|
101 |
+
if type(x) is complex:
|
102 |
+
if x.imag:
|
103 |
+
return False
|
104 |
+
x = x.real
|
105 |
+
return x <= 0.0 and round(x) == x
|
106 |
+
|
107 |
+
mpf = float
|
108 |
+
mpc = complex
|
109 |
+
|
110 |
+
def convert(ctx, x):
|
111 |
+
try:
|
112 |
+
return float(x)
|
113 |
+
except:
|
114 |
+
return complex(x)
|
115 |
+
|
116 |
+
power = staticmethod(math2.pow)
|
117 |
+
sqrt = staticmethod(math2.sqrt)
|
118 |
+
exp = staticmethod(math2.exp)
|
119 |
+
ln = log = staticmethod(math2.log)
|
120 |
+
cos = staticmethod(math2.cos)
|
121 |
+
sin = staticmethod(math2.sin)
|
122 |
+
tan = staticmethod(math2.tan)
|
123 |
+
cos_sin = staticmethod(math2.cos_sin)
|
124 |
+
acos = staticmethod(math2.acos)
|
125 |
+
asin = staticmethod(math2.asin)
|
126 |
+
atan = staticmethod(math2.atan)
|
127 |
+
cosh = staticmethod(math2.cosh)
|
128 |
+
sinh = staticmethod(math2.sinh)
|
129 |
+
tanh = staticmethod(math2.tanh)
|
130 |
+
gamma = staticmethod(math2.gamma)
|
131 |
+
rgamma = staticmethod(math2.rgamma)
|
132 |
+
fac = factorial = staticmethod(math2.factorial)
|
133 |
+
floor = staticmethod(math2.floor)
|
134 |
+
ceil = staticmethod(math2.ceil)
|
135 |
+
cospi = staticmethod(math2.cospi)
|
136 |
+
sinpi = staticmethod(math2.sinpi)
|
137 |
+
cbrt = staticmethod(math2.cbrt)
|
138 |
+
_nthroot = staticmethod(math2.nthroot)
|
139 |
+
_ei = staticmethod(math2.ei)
|
140 |
+
_e1 = staticmethod(math2.e1)
|
141 |
+
_zeta = _zeta_int = staticmethod(math2.zeta)
|
142 |
+
|
143 |
+
# XXX: math2
|
144 |
+
def arg(ctx, z):
|
145 |
+
z = complex(z)
|
146 |
+
return math.atan2(z.imag, z.real)
|
147 |
+
|
148 |
+
def expj(ctx, x):
|
149 |
+
return ctx.exp(ctx.j*x)
|
150 |
+
|
151 |
+
def expjpi(ctx, x):
|
152 |
+
return ctx.exp(ctx.j*ctx.pi*x)
|
153 |
+
|
154 |
+
ldexp = math.ldexp
|
155 |
+
frexp = math.frexp
|
156 |
+
|
157 |
+
def mag(ctx, z):
|
158 |
+
if z:
|
159 |
+
return ctx.frexp(abs(z))[1]
|
160 |
+
return ctx.ninf
|
161 |
+
|
162 |
+
def isint(ctx, z):
|
163 |
+
if hasattr(z, "imag"): # float/int don't have .real/.imag in py2.5
|
164 |
+
if z.imag:
|
165 |
+
return False
|
166 |
+
z = z.real
|
167 |
+
try:
|
168 |
+
return z == int(z)
|
169 |
+
except:
|
170 |
+
return False
|
171 |
+
|
172 |
+
def nint_distance(ctx, z):
|
173 |
+
if hasattr(z, "imag"): # float/int don't have .real/.imag in py2.5
|
174 |
+
n = round(z.real)
|
175 |
+
else:
|
176 |
+
n = round(z)
|
177 |
+
if n == z:
|
178 |
+
return n, ctx.ninf
|
179 |
+
return n, ctx.mag(abs(z-n))
|
180 |
+
|
181 |
+
def _convert_param(ctx, z):
|
182 |
+
if type(z) is tuple:
|
183 |
+
p, q = z
|
184 |
+
return ctx.mpf(p) / q, 'R'
|
185 |
+
if hasattr(z, "imag"): # float/int don't have .real/.imag in py2.5
|
186 |
+
intz = int(z.real)
|
187 |
+
else:
|
188 |
+
intz = int(z)
|
189 |
+
if z == intz:
|
190 |
+
return intz, 'Z'
|
191 |
+
return z, 'R'
|
192 |
+
|
193 |
+
def _is_real_type(ctx, z):
|
194 |
+
return isinstance(z, float) or isinstance(z, int_types)
|
195 |
+
|
196 |
+
def _is_complex_type(ctx, z):
|
197 |
+
return isinstance(z, complex)
|
198 |
+
|
199 |
+
def hypsum(ctx, p, q, types, coeffs, z, maxterms=6000, **kwargs):
|
200 |
+
coeffs = list(coeffs)
|
201 |
+
num = range(p)
|
202 |
+
den = range(p,p+q)
|
203 |
+
tol = ctx.eps
|
204 |
+
s = t = 1.0
|
205 |
+
k = 0
|
206 |
+
while 1:
|
207 |
+
for i in num: t *= (coeffs[i]+k)
|
208 |
+
for i in den: t /= (coeffs[i]+k)
|
209 |
+
k += 1; t /= k; t *= z; s += t
|
210 |
+
if abs(t) < tol:
|
211 |
+
return s
|
212 |
+
if k > maxterms:
|
213 |
+
raise ctx.NoConvergence
|
214 |
+
|
215 |
+
def atan2(ctx, x, y):
|
216 |
+
return math.atan2(x, y)
|
217 |
+
|
218 |
+
def psi(ctx, m, z):
|
219 |
+
m = int(m)
|
220 |
+
if m == 0:
|
221 |
+
return ctx.digamma(z)
|
222 |
+
return (-1)**(m+1) * ctx.fac(m) * ctx.zeta(m+1, z)
|
223 |
+
|
224 |
+
digamma = staticmethod(math2.digamma)
|
225 |
+
|
226 |
+
def harmonic(ctx, x):
|
227 |
+
x = ctx.convert(x)
|
228 |
+
if x == 0 or x == 1:
|
229 |
+
return x
|
230 |
+
return ctx.digamma(x+1) + ctx.euler
|
231 |
+
|
232 |
+
nstr = str
|
233 |
+
|
234 |
+
def to_fixed(ctx, x, prec):
|
235 |
+
return int(math.ldexp(x, prec))
|
236 |
+
|
237 |
+
def rand(ctx):
|
238 |
+
import random
|
239 |
+
return random.random()
|
240 |
+
|
241 |
+
_erf = staticmethod(math2.erf)
|
242 |
+
_erfc = staticmethod(math2.erfc)
|
243 |
+
|
244 |
+
def sum_accurately(ctx, terms, check_step=1):
|
245 |
+
s = ctx.zero
|
246 |
+
k = 0
|
247 |
+
for term in terms():
|
248 |
+
s += term
|
249 |
+
if (not k % check_step) and term:
|
250 |
+
if abs(term) <= 1e-18*abs(s):
|
251 |
+
break
|
252 |
+
k += 1
|
253 |
+
return s
|
venv/lib/python3.10/site-packages/mpmath/ctx_iv.py
ADDED
@@ -0,0 +1,551 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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prec_to_dps, dps_to_prec, repr_dps,
|
10 |
+
round_floor, round_ceiling,
|
11 |
+
fzero, finf, fninf, fnan,
|
12 |
+
mpf_le, mpf_neg,
|
13 |
+
from_int, from_float, from_str, from_rational,
|
14 |
+
mpi_mid, mpi_delta, mpi_str,
|
15 |
+
mpi_abs, mpi_pos, mpi_neg, mpi_add, mpi_sub,
|
16 |
+
mpi_mul, mpi_div, mpi_pow_int, mpi_pow,
|
17 |
+
mpi_from_str,
|
18 |
+
mpci_pos, mpci_neg, mpci_add, mpci_sub, mpci_mul, mpci_div, mpci_pow,
|
19 |
+
mpci_abs, mpci_pow, mpci_exp, mpci_log,
|
20 |
+
ComplexResult,
|
21 |
+
mpf_hash, mpc_hash)
|
22 |
+
from .matrices.matrices import _matrix
|
23 |
+
|
24 |
+
mpi_zero = (fzero, fzero)
|
25 |
+
|
26 |
+
from .ctx_base import StandardBaseContext
|
27 |
+
|
28 |
+
new = object.__new__
|
29 |
+
|
30 |
+
def convert_mpf_(x, prec, rounding):
|
31 |
+
if hasattr(x, "_mpf_"): return x._mpf_
|
32 |
+
if isinstance(x, int_types): return from_int(x, prec, rounding)
|
33 |
+
if isinstance(x, float): return from_float(x, prec, rounding)
|
34 |
+
if isinstance(x, basestring): return from_str(x, prec, rounding)
|
35 |
+
raise NotImplementedError
|
36 |
+
|
37 |
+
|
38 |
+
class ivmpf(object):
|
39 |
+
"""
|
40 |
+
Interval arithmetic class. Precision is controlled by iv.prec.
|
41 |
+
"""
|
42 |
+
|
43 |
+
def __new__(cls, x=0):
|
44 |
+
return cls.ctx.convert(x)
|
45 |
+
|
46 |
+
def cast(self, cls, f_convert):
|
47 |
+
a, b = self._mpi_
|
48 |
+
if a == b:
|
49 |
+
return cls(f_convert(a))
|
50 |
+
raise ValueError
|
51 |
+
|
52 |
+
def __int__(self):
|
53 |
+
return self.cast(int, libmp.to_int)
|
54 |
+
|
55 |
+
def __float__(self):
|
56 |
+
return self.cast(float, libmp.to_float)
|
57 |
+
|
58 |
+
def __complex__(self):
|
59 |
+
return self.cast(complex, libmp.to_float)
|
60 |
+
|
61 |
+
def __hash__(self):
|
62 |
+
a, b = self._mpi_
|
63 |
+
if a == b:
|
64 |
+
return mpf_hash(a)
|
65 |
+
else:
|
66 |
+
return hash(self._mpi_)
|
67 |
+
|
68 |
+
@property
|
69 |
+
def real(self): return self
|
70 |
+
|
71 |
+
@property
|
72 |
+
def imag(self): return self.ctx.zero
|
73 |
+
|
74 |
+
def conjugate(self): return self
|
75 |
+
|
76 |
+
@property
|
77 |
+
def a(self):
|
78 |
+
a, b = self._mpi_
|
79 |
+
return self.ctx.make_mpf((a, a))
|
80 |
+
|
81 |
+
@property
|
82 |
+
def b(self):
|
83 |
+
a, b = self._mpi_
|
84 |
+
return self.ctx.make_mpf((b, b))
|
85 |
+
|
86 |
+
@property
|
87 |
+
def mid(self):
|
88 |
+
ctx = self.ctx
|
89 |
+
v = mpi_mid(self._mpi_, ctx.prec)
|
90 |
+
return ctx.make_mpf((v, v))
|
91 |
+
|
92 |
+
@property
|
93 |
+
def delta(self):
|
94 |
+
ctx = self.ctx
|
95 |
+
v = mpi_delta(self._mpi_, ctx.prec)
|
96 |
+
return ctx.make_mpf((v,v))
|
97 |
+
|
98 |
+
@property
|
99 |
+
def _mpci_(self):
|
100 |
+
return self._mpi_, mpi_zero
|
101 |
+
|
102 |
+
def _compare(*args):
|
103 |
+
raise TypeError("no ordering relation is defined for intervals")
|
104 |
+
|
105 |
+
__gt__ = _compare
|
106 |
+
__le__ = _compare
|
107 |
+
__gt__ = _compare
|
108 |
+
__ge__ = _compare
|
109 |
+
|
110 |
+
def __contains__(self, t):
|
111 |
+
t = self.ctx.mpf(t)
|
112 |
+
return (self.a <= t.a) and (t.b <= self.b)
|
113 |
+
|
114 |
+
def __str__(self):
|
115 |
+
return mpi_str(self._mpi_, self.ctx.prec)
|
116 |
+
|
117 |
+
def __repr__(self):
|
118 |
+
if self.ctx.pretty:
|
119 |
+
return str(self)
|
120 |
+
a, b = self._mpi_
|
121 |
+
n = repr_dps(self.ctx.prec)
|
122 |
+
a = libmp.to_str(a, n)
|
123 |
+
b = libmp.to_str(b, n)
|
124 |
+
return "mpi(%r, %r)" % (a, b)
|
125 |
+
|
126 |
+
def _compare(s, t, cmpfun):
|
127 |
+
if not hasattr(t, "_mpi_"):
|
128 |
+
try:
|
129 |
+
t = s.ctx.convert(t)
|
130 |
+
except:
|
131 |
+
return NotImplemented
|
132 |
+
return cmpfun(s._mpi_, t._mpi_)
|
133 |
+
|
134 |
+
def __eq__(s, t): return s._compare(t, libmp.mpi_eq)
|
135 |
+
def __ne__(s, t): return s._compare(t, libmp.mpi_ne)
|
136 |
+
def __lt__(s, t): return s._compare(t, libmp.mpi_lt)
|
137 |
+
def __le__(s, t): return s._compare(t, libmp.mpi_le)
|
138 |
+
def __gt__(s, t): return s._compare(t, libmp.mpi_gt)
|
139 |
+
def __ge__(s, t): return s._compare(t, libmp.mpi_ge)
|
140 |
+
|
141 |
+
def __abs__(self):
|
142 |
+
return self.ctx.make_mpf(mpi_abs(self._mpi_, self.ctx.prec))
|
143 |
+
def __pos__(self):
|
144 |
+
return self.ctx.make_mpf(mpi_pos(self._mpi_, self.ctx.prec))
|
145 |
+
def __neg__(self):
|
146 |
+
return self.ctx.make_mpf(mpi_neg(self._mpi_, self.ctx.prec))
|
147 |
+
|
148 |
+
def ae(s, t, rel_eps=None, abs_eps=None):
|
149 |
+
return s.ctx.almosteq(s, t, rel_eps, abs_eps)
|
150 |
+
|
151 |
+
class ivmpc(object):
|
152 |
+
|
153 |
+
def __new__(cls, re=0, im=0):
|
154 |
+
re = cls.ctx.convert(re)
|
155 |
+
im = cls.ctx.convert(im)
|
156 |
+
y = new(cls)
|
157 |
+
y._mpci_ = re._mpi_, im._mpi_
|
158 |
+
return y
|
159 |
+
|
160 |
+
def __hash__(self):
|
161 |
+
(a, b), (c,d) = self._mpci_
|
162 |
+
if a == b and c == d:
|
163 |
+
return mpc_hash((a, c))
|
164 |
+
else:
|
165 |
+
return hash(self._mpci_)
|
166 |
+
|
167 |
+
def __repr__(s):
|
168 |
+
if s.ctx.pretty:
|
169 |
+
return str(s)
|
170 |
+
return "iv.mpc(%s, %s)" % (repr(s.real), repr(s.imag))
|
171 |
+
|
172 |
+
def __str__(s):
|
173 |
+
return "(%s + %s*j)" % (str(s.real), str(s.imag))
|
174 |
+
|
175 |
+
@property
|
176 |
+
def a(self):
|
177 |
+
(a, b), (c,d) = self._mpci_
|
178 |
+
return self.ctx.make_mpf((a, a))
|
179 |
+
|
180 |
+
@property
|
181 |
+
def b(self):
|
182 |
+
(a, b), (c,d) = self._mpci_
|
183 |
+
return self.ctx.make_mpf((b, b))
|
184 |
+
|
185 |
+
@property
|
186 |
+
def c(self):
|
187 |
+
(a, b), (c,d) = self._mpci_
|
188 |
+
return self.ctx.make_mpf((c, c))
|
189 |
+
|
190 |
+
@property
|
191 |
+
def d(self):
|
192 |
+
(a, b), (c,d) = self._mpci_
|
193 |
+
return self.ctx.make_mpf((d, d))
|
194 |
+
|
195 |
+
@property
|
196 |
+
def real(s):
|
197 |
+
return s.ctx.make_mpf(s._mpci_[0])
|
198 |
+
|
199 |
+
@property
|
200 |
+
def imag(s):
|
201 |
+
return s.ctx.make_mpf(s._mpci_[1])
|
202 |
+
|
203 |
+
def conjugate(s):
|
204 |
+
a, b = s._mpci_
|
205 |
+
return s.ctx.make_mpc((a, mpf_neg(b)))
|
206 |
+
|
207 |
+
def overlap(s, t):
|
208 |
+
t = s.ctx.convert(t)
|
209 |
+
real_overlap = (s.a <= t.a <= s.b) or (s.a <= t.b <= s.b) or (t.a <= s.a <= t.b) or (t.a <= s.b <= t.b)
|
210 |
+
imag_overlap = (s.c <= t.c <= s.d) or (s.c <= t.d <= s.d) or (t.c <= s.c <= t.d) or (t.c <= s.d <= t.d)
|
211 |
+
return real_overlap and imag_overlap
|
212 |
+
|
213 |
+
def __contains__(s, t):
|
214 |
+
t = s.ctx.convert(t)
|
215 |
+
return t.real in s.real and t.imag in s.imag
|
216 |
+
|
217 |
+
def _compare(s, t, ne=False):
|
218 |
+
if not isinstance(t, s.ctx._types):
|
219 |
+
try:
|
220 |
+
t = s.ctx.convert(t)
|
221 |
+
except:
|
222 |
+
return NotImplemented
|
223 |
+
if hasattr(t, '_mpi_'):
|
224 |
+
tval = t._mpi_, mpi_zero
|
225 |
+
elif hasattr(t, '_mpci_'):
|
226 |
+
tval = t._mpci_
|
227 |
+
if ne:
|
228 |
+
return s._mpci_ != tval
|
229 |
+
return s._mpci_ == tval
|
230 |
+
|
231 |
+
def __eq__(s, t): return s._compare(t)
|
232 |
+
def __ne__(s, t): return s._compare(t, True)
|
233 |
+
|
234 |
+
def __lt__(s, t): raise TypeError("complex intervals cannot be ordered")
|
235 |
+
__le__ = __gt__ = __ge__ = __lt__
|
236 |
+
|
237 |
+
def __neg__(s): return s.ctx.make_mpc(mpci_neg(s._mpci_, s.ctx.prec))
|
238 |
+
def __pos__(s): return s.ctx.make_mpc(mpci_pos(s._mpci_, s.ctx.prec))
|
239 |
+
def __abs__(s): return s.ctx.make_mpf(mpci_abs(s._mpci_, s.ctx.prec))
|
240 |
+
|
241 |
+
def ae(s, t, rel_eps=None, abs_eps=None):
|
242 |
+
return s.ctx.almosteq(s, t, rel_eps, abs_eps)
|
243 |
+
|
244 |
+
def _binary_op(f_real, f_complex):
|
245 |
+
def g_complex(ctx, sval, tval):
|
246 |
+
return ctx.make_mpc(f_complex(sval, tval, ctx.prec))
|
247 |
+
def g_real(ctx, sval, tval):
|
248 |
+
try:
|
249 |
+
return ctx.make_mpf(f_real(sval, tval, ctx.prec))
|
250 |
+
except ComplexResult:
|
251 |
+
sval = (sval, mpi_zero)
|
252 |
+
tval = (tval, mpi_zero)
|
253 |
+
return g_complex(ctx, sval, tval)
|
254 |
+
def lop_real(s, t):
|
255 |
+
if isinstance(t, _matrix): return NotImplemented
|
256 |
+
ctx = s.ctx
|
257 |
+
if not isinstance(t, ctx._types): t = ctx.convert(t)
|
258 |
+
if hasattr(t, "_mpi_"): return g_real(ctx, s._mpi_, t._mpi_)
|
259 |
+
if hasattr(t, "_mpci_"): return g_complex(ctx, (s._mpi_, mpi_zero), t._mpci_)
|
260 |
+
return NotImplemented
|
261 |
+
def rop_real(s, t):
|
262 |
+
ctx = s.ctx
|
263 |
+
if not isinstance(t, ctx._types): t = ctx.convert(t)
|
264 |
+
if hasattr(t, "_mpi_"): return g_real(ctx, t._mpi_, s._mpi_)
|
265 |
+
if hasattr(t, "_mpci_"): return g_complex(ctx, t._mpci_, (s._mpi_, mpi_zero))
|
266 |
+
return NotImplemented
|
267 |
+
def lop_complex(s, t):
|
268 |
+
if isinstance(t, _matrix): return NotImplemented
|
269 |
+
ctx = s.ctx
|
270 |
+
if not isinstance(t, s.ctx._types):
|
271 |
+
try:
|
272 |
+
t = s.ctx.convert(t)
|
273 |
+
except (ValueError, TypeError):
|
274 |
+
return NotImplemented
|
275 |
+
return g_complex(ctx, s._mpci_, t._mpci_)
|
276 |
+
def rop_complex(s, t):
|
277 |
+
ctx = s.ctx
|
278 |
+
if not isinstance(t, s.ctx._types):
|
279 |
+
t = s.ctx.convert(t)
|
280 |
+
return g_complex(ctx, t._mpci_, s._mpci_)
|
281 |
+
return lop_real, rop_real, lop_complex, rop_complex
|
282 |
+
|
283 |
+
ivmpf.__add__, ivmpf.__radd__, ivmpc.__add__, ivmpc.__radd__ = _binary_op(mpi_add, mpci_add)
|
284 |
+
ivmpf.__sub__, ivmpf.__rsub__, ivmpc.__sub__, ivmpc.__rsub__ = _binary_op(mpi_sub, mpci_sub)
|
285 |
+
ivmpf.__mul__, ivmpf.__rmul__, ivmpc.__mul__, ivmpc.__rmul__ = _binary_op(mpi_mul, mpci_mul)
|
286 |
+
ivmpf.__div__, ivmpf.__rdiv__, ivmpc.__div__, ivmpc.__rdiv__ = _binary_op(mpi_div, mpci_div)
|
287 |
+
ivmpf.__pow__, ivmpf.__rpow__, ivmpc.__pow__, ivmpc.__rpow__ = _binary_op(mpi_pow, mpci_pow)
|
288 |
+
|
289 |
+
ivmpf.__truediv__ = ivmpf.__div__; ivmpf.__rtruediv__ = ivmpf.__rdiv__
|
290 |
+
ivmpc.__truediv__ = ivmpc.__div__; ivmpc.__rtruediv__ = ivmpc.__rdiv__
|
291 |
+
|
292 |
+
class ivmpf_constant(ivmpf):
|
293 |
+
def __new__(cls, f):
|
294 |
+
self = new(cls)
|
295 |
+
self._f = f
|
296 |
+
return self
|
297 |
+
def _get_mpi_(self):
|
298 |
+
prec = self.ctx._prec[0]
|
299 |
+
a = self._f(prec, round_floor)
|
300 |
+
b = self._f(prec, round_ceiling)
|
301 |
+
return a, b
|
302 |
+
_mpi_ = property(_get_mpi_)
|
303 |
+
|
304 |
+
class MPIntervalContext(StandardBaseContext):
|
305 |
+
|
306 |
+
def __init__(ctx):
|
307 |
+
ctx.mpf = type('ivmpf', (ivmpf,), {})
|
308 |
+
ctx.mpc = type('ivmpc', (ivmpc,), {})
|
309 |
+
ctx._types = (ctx.mpf, ctx.mpc)
|
310 |
+
ctx._constant = type('ivmpf_constant', (ivmpf_constant,), {})
|
311 |
+
ctx._prec = [53]
|
312 |
+
ctx._set_prec(53)
|
313 |
+
ctx._constant._ctxdata = ctx.mpf._ctxdata = ctx.mpc._ctxdata = [ctx.mpf, new, ctx._prec]
|
314 |
+
ctx._constant.ctx = ctx.mpf.ctx = ctx.mpc.ctx = ctx
|
315 |
+
ctx.pretty = False
|
316 |
+
StandardBaseContext.__init__(ctx)
|
317 |
+
ctx._init_builtins()
|
318 |
+
|
319 |
+
def _mpi(ctx, a, b=None):
|
320 |
+
if b is None:
|
321 |
+
return ctx.mpf(a)
|
322 |
+
return ctx.mpf((a,b))
|
323 |
+
|
324 |
+
def _init_builtins(ctx):
|
325 |
+
ctx.one = ctx.mpf(1)
|
326 |
+
ctx.zero = ctx.mpf(0)
|
327 |
+
ctx.inf = ctx.mpf('inf')
|
328 |
+
ctx.ninf = -ctx.inf
|
329 |
+
ctx.nan = ctx.mpf('nan')
|
330 |
+
ctx.j = ctx.mpc(0,1)
|
331 |
+
ctx.exp = ctx._wrap_mpi_function(libmp.mpi_exp, libmp.mpci_exp)
|
332 |
+
ctx.sqrt = ctx._wrap_mpi_function(libmp.mpi_sqrt)
|
333 |
+
ctx.ln = ctx._wrap_mpi_function(libmp.mpi_log, libmp.mpci_log)
|
334 |
+
ctx.cos = ctx._wrap_mpi_function(libmp.mpi_cos, libmp.mpci_cos)
|
335 |
+
ctx.sin = ctx._wrap_mpi_function(libmp.mpi_sin, libmp.mpci_sin)
|
336 |
+
ctx.tan = ctx._wrap_mpi_function(libmp.mpi_tan)
|
337 |
+
ctx.gamma = ctx._wrap_mpi_function(libmp.mpi_gamma, libmp.mpci_gamma)
|
338 |
+
ctx.loggamma = ctx._wrap_mpi_function(libmp.mpi_loggamma, libmp.mpci_loggamma)
|
339 |
+
ctx.rgamma = ctx._wrap_mpi_function(libmp.mpi_rgamma, libmp.mpci_rgamma)
|
340 |
+
ctx.factorial = ctx._wrap_mpi_function(libmp.mpi_factorial, libmp.mpci_factorial)
|
341 |
+
ctx.fac = ctx.factorial
|
342 |
+
|
343 |
+
ctx.eps = ctx._constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1))
|
344 |
+
ctx.pi = ctx._constant(libmp.mpf_pi)
|
345 |
+
ctx.e = ctx._constant(libmp.mpf_e)
|
346 |
+
ctx.ln2 = ctx._constant(libmp.mpf_ln2)
|
347 |
+
ctx.ln10 = ctx._constant(libmp.mpf_ln10)
|
348 |
+
ctx.phi = ctx._constant(libmp.mpf_phi)
|
349 |
+
ctx.euler = ctx._constant(libmp.mpf_euler)
|
350 |
+
ctx.catalan = ctx._constant(libmp.mpf_catalan)
|
351 |
+
ctx.glaisher = ctx._constant(libmp.mpf_glaisher)
|
352 |
+
ctx.khinchin = ctx._constant(libmp.mpf_khinchin)
|
353 |
+
ctx.twinprime = ctx._constant(libmp.mpf_twinprime)
|
354 |
+
|
355 |
+
def _wrap_mpi_function(ctx, f_real, f_complex=None):
|
356 |
+
def g(x, **kwargs):
|
357 |
+
if kwargs:
|
358 |
+
prec = kwargs.get('prec', ctx._prec[0])
|
359 |
+
else:
|
360 |
+
prec = ctx._prec[0]
|
361 |
+
x = ctx.convert(x)
|
362 |
+
if hasattr(x, "_mpi_"):
|
363 |
+
return ctx.make_mpf(f_real(x._mpi_, prec))
|
364 |
+
if hasattr(x, "_mpci_"):
|
365 |
+
return ctx.make_mpc(f_complex(x._mpci_, prec))
|
366 |
+
raise ValueError
|
367 |
+
return g
|
368 |
+
|
369 |
+
@classmethod
|
370 |
+
def _wrap_specfun(cls, name, f, wrap):
|
371 |
+
if wrap:
|
372 |
+
def f_wrapped(ctx, *args, **kwargs):
|
373 |
+
convert = ctx.convert
|
374 |
+
args = [convert(a) for a in args]
|
375 |
+
prec = ctx.prec
|
376 |
+
try:
|
377 |
+
ctx.prec += 10
|
378 |
+
retval = f(ctx, *args, **kwargs)
|
379 |
+
finally:
|
380 |
+
ctx.prec = prec
|
381 |
+
return +retval
|
382 |
+
else:
|
383 |
+
f_wrapped = f
|
384 |
+
setattr(cls, name, f_wrapped)
|
385 |
+
|
386 |
+
def _set_prec(ctx, n):
|
387 |
+
ctx._prec[0] = max(1, int(n))
|
388 |
+
ctx._dps = prec_to_dps(n)
|
389 |
+
|
390 |
+
def _set_dps(ctx, n):
|
391 |
+
ctx._prec[0] = dps_to_prec(n)
|
392 |
+
ctx._dps = max(1, int(n))
|
393 |
+
|
394 |
+
prec = property(lambda ctx: ctx._prec[0], _set_prec)
|
395 |
+
dps = property(lambda ctx: ctx._dps, _set_dps)
|
396 |
+
|
397 |
+
def make_mpf(ctx, v):
|
398 |
+
a = new(ctx.mpf)
|
399 |
+
a._mpi_ = v
|
400 |
+
return a
|
401 |
+
|
402 |
+
def make_mpc(ctx, v):
|
403 |
+
a = new(ctx.mpc)
|
404 |
+
a._mpci_ = v
|
405 |
+
return a
|
406 |
+
|
407 |
+
def _mpq(ctx, pq):
|
408 |
+
p, q = pq
|
409 |
+
a = libmp.from_rational(p, q, ctx.prec, round_floor)
|
410 |
+
b = libmp.from_rational(p, q, ctx.prec, round_ceiling)
|
411 |
+
return ctx.make_mpf((a, b))
|
412 |
+
|
413 |
+
def convert(ctx, x):
|
414 |
+
if isinstance(x, (ctx.mpf, ctx.mpc)):
|
415 |
+
return x
|
416 |
+
if isinstance(x, ctx._constant):
|
417 |
+
return +x
|
418 |
+
if isinstance(x, complex) or hasattr(x, "_mpc_"):
|
419 |
+
re = ctx.convert(x.real)
|
420 |
+
im = ctx.convert(x.imag)
|
421 |
+
return ctx.mpc(re,im)
|
422 |
+
if isinstance(x, basestring):
|
423 |
+
v = mpi_from_str(x, ctx.prec)
|
424 |
+
return ctx.make_mpf(v)
|
425 |
+
if hasattr(x, "_mpi_"):
|
426 |
+
a, b = x._mpi_
|
427 |
+
else:
|
428 |
+
try:
|
429 |
+
a, b = x
|
430 |
+
except (TypeError, ValueError):
|
431 |
+
a = b = x
|
432 |
+
if hasattr(a, "_mpi_"):
|
433 |
+
a = a._mpi_[0]
|
434 |
+
else:
|
435 |
+
a = convert_mpf_(a, ctx.prec, round_floor)
|
436 |
+
if hasattr(b, "_mpi_"):
|
437 |
+
b = b._mpi_[1]
|
438 |
+
else:
|
439 |
+
b = convert_mpf_(b, ctx.prec, round_ceiling)
|
440 |
+
if a == fnan or b == fnan:
|
441 |
+
a = fninf
|
442 |
+
b = finf
|
443 |
+
assert mpf_le(a, b), "endpoints must be properly ordered"
|
444 |
+
return ctx.make_mpf((a, b))
|
445 |
+
|
446 |
+
def nstr(ctx, x, n=5, **kwargs):
|
447 |
+
x = ctx.convert(x)
|
448 |
+
if hasattr(x, "_mpi_"):
|
449 |
+
return libmp.mpi_to_str(x._mpi_, n, **kwargs)
|
450 |
+
if hasattr(x, "_mpci_"):
|
451 |
+
re = libmp.mpi_to_str(x._mpci_[0], n, **kwargs)
|
452 |
+
im = libmp.mpi_to_str(x._mpci_[1], n, **kwargs)
|
453 |
+
return "(%s + %s*j)" % (re, im)
|
454 |
+
|
455 |
+
def mag(ctx, x):
|
456 |
+
x = ctx.convert(x)
|
457 |
+
if isinstance(x, ctx.mpc):
|
458 |
+
return max(ctx.mag(x.real), ctx.mag(x.imag)) + 1
|
459 |
+
a, b = libmp.mpi_abs(x._mpi_)
|
460 |
+
sign, man, exp, bc = b
|
461 |
+
if man:
|
462 |
+
return exp+bc
|
463 |
+
if b == fzero:
|
464 |
+
return ctx.ninf
|
465 |
+
if b == fnan:
|
466 |
+
return ctx.nan
|
467 |
+
return ctx.inf
|
468 |
+
|
469 |
+
def isnan(ctx, x):
|
470 |
+
return False
|
471 |
+
|
472 |
+
def isinf(ctx, x):
|
473 |
+
return x == ctx.inf
|
474 |
+
|
475 |
+
def isint(ctx, x):
|
476 |
+
x = ctx.convert(x)
|
477 |
+
a, b = x._mpi_
|
478 |
+
if a == b:
|
479 |
+
sign, man, exp, bc = a
|
480 |
+
if man:
|
481 |
+
return exp >= 0
|
482 |
+
return a == fzero
|
483 |
+
return None
|
484 |
+
|
485 |
+
def ldexp(ctx, x, n):
|
486 |
+
a, b = ctx.convert(x)._mpi_
|
487 |
+
a = libmp.mpf_shift(a, n)
|
488 |
+
b = libmp.mpf_shift(b, n)
|
489 |
+
return ctx.make_mpf((a,b))
|
490 |
+
|
491 |
+
def absmin(ctx, x):
|
492 |
+
return abs(ctx.convert(x)).a
|
493 |
+
|
494 |
+
def absmax(ctx, x):
|
495 |
+
return abs(ctx.convert(x)).b
|
496 |
+
|
497 |
+
def atan2(ctx, y, x):
|
498 |
+
y = ctx.convert(y)._mpi_
|
499 |
+
x = ctx.convert(x)._mpi_
|
500 |
+
return ctx.make_mpf(libmp.mpi_atan2(y,x,ctx.prec))
|
501 |
+
|
502 |
+
def _convert_param(ctx, x):
|
503 |
+
if isinstance(x, libmp.int_types):
|
504 |
+
return x, 'Z'
|
505 |
+
if isinstance(x, tuple):
|
506 |
+
p, q = x
|
507 |
+
return (ctx.mpf(p) / ctx.mpf(q), 'R')
|
508 |
+
x = ctx.convert(x)
|
509 |
+
if isinstance(x, ctx.mpf):
|
510 |
+
return x, 'R'
|
511 |
+
if isinstance(x, ctx.mpc):
|
512 |
+
return x, 'C'
|
513 |
+
raise ValueError
|
514 |
+
|
515 |
+
def _is_real_type(ctx, z):
|
516 |
+
return isinstance(z, ctx.mpf) or isinstance(z, int_types)
|
517 |
+
|
518 |
+
def _is_complex_type(ctx, z):
|
519 |
+
return isinstance(z, ctx.mpc)
|
520 |
+
|
521 |
+
def hypsum(ctx, p, q, types, coeffs, z, maxterms=6000, **kwargs):
|
522 |
+
coeffs = list(coeffs)
|
523 |
+
num = range(p)
|
524 |
+
den = range(p,p+q)
|
525 |
+
#tol = ctx.eps
|
526 |
+
s = t = ctx.one
|
527 |
+
k = 0
|
528 |
+
while 1:
|
529 |
+
for i in num: t *= (coeffs[i]+k)
|
530 |
+
for i in den: t /= (coeffs[i]+k)
|
531 |
+
k += 1; t /= k; t *= z; s += t
|
532 |
+
if t == 0:
|
533 |
+
return s
|
534 |
+
#if abs(t) < tol:
|
535 |
+
# return s
|
536 |
+
if k > maxterms:
|
537 |
+
raise ctx.NoConvergence
|
538 |
+
|
539 |
+
|
540 |
+
# Register with "numbers" ABC
|
541 |
+
# We do not subclass, hence we do not use the @abstractmethod checks. While
|
542 |
+
# this is less invasive it may turn out that we do not actually support
|
543 |
+
# parts of the expected interfaces. See
|
544 |
+
# http://docs.python.org/2/library/numbers.html for list of abstract
|
545 |
+
# methods.
|
546 |
+
try:
|
547 |
+
import numbers
|
548 |
+
numbers.Complex.register(ivmpc)
|
549 |
+
numbers.Real.register(ivmpf)
|
550 |
+
except ImportError:
|
551 |
+
pass
|
venv/lib/python3.10/site-packages/mpmath/ctx_mp.py
ADDED
@@ -0,0 +1,1339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module defines the mpf, mpc classes, and standard functions for
|
3 |
+
operating with them.
|
4 |
+
"""
|
5 |
+
__docformat__ = 'plaintext'
|
6 |
+
|
7 |
+
import functools
|
8 |
+
|
9 |
+
import re
|
10 |
+
|
11 |
+
from .ctx_base import StandardBaseContext
|
12 |
+
|
13 |
+
from .libmp.backend import basestring, BACKEND
|
14 |
+
|
15 |
+
from . import libmp
|
16 |
+
|
17 |
+
from .libmp import (MPZ, MPZ_ZERO, MPZ_ONE, int_types, repr_dps,
|
18 |
+
round_floor, round_ceiling, dps_to_prec, round_nearest, prec_to_dps,
|
19 |
+
ComplexResult, to_pickable, from_pickable, normalize,
|
20 |
+
from_int, from_float, from_str, to_int, to_float, to_str,
|
21 |
+
from_rational, from_man_exp,
|
22 |
+
fone, fzero, finf, fninf, fnan,
|
23 |
+
mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int,
|
24 |
+
mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod,
|
25 |
+
mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge,
|
26 |
+
mpf_hash, mpf_rand,
|
27 |
+
mpf_sum,
|
28 |
+
bitcount, to_fixed,
|
29 |
+
mpc_to_str,
|
30 |
+
mpc_to_complex, mpc_hash, mpc_pos, mpc_is_nonzero, mpc_neg, mpc_conjugate,
|
31 |
+
mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf,
|
32 |
+
mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int,
|
33 |
+
mpc_mpf_div,
|
34 |
+
mpf_pow,
|
35 |
+
mpf_pi, mpf_degree, mpf_e, mpf_phi, mpf_ln2, mpf_ln10,
|
36 |
+
mpf_euler, mpf_catalan, mpf_apery, mpf_khinchin,
|
37 |
+
mpf_glaisher, mpf_twinprime, mpf_mertens,
|
38 |
+
int_types)
|
39 |
+
|
40 |
+
from . import function_docs
|
41 |
+
from . import rational
|
42 |
+
|
43 |
+
new = object.__new__
|
44 |
+
|
45 |
+
get_complex = re.compile(r'^\(?(?P<re>[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?)??'
|
46 |
+
r'(?P<im>[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?j)?\)?$')
|
47 |
+
|
48 |
+
if BACKEND == 'sage':
|
49 |
+
from sage.libs.mpmath.ext_main import Context as BaseMPContext
|
50 |
+
# pickle hack
|
51 |
+
import sage.libs.mpmath.ext_main as _mpf_module
|
52 |
+
else:
|
53 |
+
from .ctx_mp_python import PythonMPContext as BaseMPContext
|
54 |
+
from . import ctx_mp_python as _mpf_module
|
55 |
+
|
56 |
+
from .ctx_mp_python import _mpf, _mpc, mpnumeric
|
57 |
+
|
58 |
+
class MPContext(BaseMPContext, StandardBaseContext):
|
59 |
+
"""
|
60 |
+
Context for multiprecision arithmetic with a global precision.
|
61 |
+
"""
|
62 |
+
|
63 |
+
def __init__(ctx):
|
64 |
+
BaseMPContext.__init__(ctx)
|
65 |
+
ctx.trap_complex = False
|
66 |
+
ctx.pretty = False
|
67 |
+
ctx.types = [ctx.mpf, ctx.mpc, ctx.constant]
|
68 |
+
ctx._mpq = rational.mpq
|
69 |
+
ctx.default()
|
70 |
+
StandardBaseContext.__init__(ctx)
|
71 |
+
|
72 |
+
ctx.mpq = rational.mpq
|
73 |
+
ctx.init_builtins()
|
74 |
+
|
75 |
+
ctx.hyp_summators = {}
|
76 |
+
|
77 |
+
ctx._init_aliases()
|
78 |
+
|
79 |
+
# XXX: automate
|
80 |
+
try:
|
81 |
+
ctx.bernoulli.im_func.func_doc = function_docs.bernoulli
|
82 |
+
ctx.primepi.im_func.func_doc = function_docs.primepi
|
83 |
+
ctx.psi.im_func.func_doc = function_docs.psi
|
84 |
+
ctx.atan2.im_func.func_doc = function_docs.atan2
|
85 |
+
except AttributeError:
|
86 |
+
# python 3
|
87 |
+
ctx.bernoulli.__func__.func_doc = function_docs.bernoulli
|
88 |
+
ctx.primepi.__func__.func_doc = function_docs.primepi
|
89 |
+
ctx.psi.__func__.func_doc = function_docs.psi
|
90 |
+
ctx.atan2.__func__.func_doc = function_docs.atan2
|
91 |
+
|
92 |
+
ctx.digamma.func_doc = function_docs.digamma
|
93 |
+
ctx.cospi.func_doc = function_docs.cospi
|
94 |
+
ctx.sinpi.func_doc = function_docs.sinpi
|
95 |
+
|
96 |
+
def init_builtins(ctx):
|
97 |
+
|
98 |
+
mpf = ctx.mpf
|
99 |
+
mpc = ctx.mpc
|
100 |
+
|
101 |
+
# Exact constants
|
102 |
+
ctx.one = ctx.make_mpf(fone)
|
103 |
+
ctx.zero = ctx.make_mpf(fzero)
|
104 |
+
ctx.j = ctx.make_mpc((fzero,fone))
|
105 |
+
ctx.inf = ctx.make_mpf(finf)
|
106 |
+
ctx.ninf = ctx.make_mpf(fninf)
|
107 |
+
ctx.nan = ctx.make_mpf(fnan)
|
108 |
+
|
109 |
+
eps = ctx.constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1),
|
110 |
+
"epsilon of working precision", "eps")
|
111 |
+
ctx.eps = eps
|
112 |
+
|
113 |
+
# Approximate constants
|
114 |
+
ctx.pi = ctx.constant(mpf_pi, "pi", "pi")
|
115 |
+
ctx.ln2 = ctx.constant(mpf_ln2, "ln(2)", "ln2")
|
116 |
+
ctx.ln10 = ctx.constant(mpf_ln10, "ln(10)", "ln10")
|
117 |
+
ctx.phi = ctx.constant(mpf_phi, "Golden ratio phi", "phi")
|
118 |
+
ctx.e = ctx.constant(mpf_e, "e = exp(1)", "e")
|
119 |
+
ctx.euler = ctx.constant(mpf_euler, "Euler's constant", "euler")
|
120 |
+
ctx.catalan = ctx.constant(mpf_catalan, "Catalan's constant", "catalan")
|
121 |
+
ctx.khinchin = ctx.constant(mpf_khinchin, "Khinchin's constant", "khinchin")
|
122 |
+
ctx.glaisher = ctx.constant(mpf_glaisher, "Glaisher's constant", "glaisher")
|
123 |
+
ctx.apery = ctx.constant(mpf_apery, "Apery's constant", "apery")
|
124 |
+
ctx.degree = ctx.constant(mpf_degree, "1 deg = pi / 180", "degree")
|
125 |
+
ctx.twinprime = ctx.constant(mpf_twinprime, "Twin prime constant", "twinprime")
|
126 |
+
ctx.mertens = ctx.constant(mpf_mertens, "Mertens' constant", "mertens")
|
127 |
+
|
128 |
+
# Standard functions
|
129 |
+
ctx.sqrt = ctx._wrap_libmp_function(libmp.mpf_sqrt, libmp.mpc_sqrt)
|
130 |
+
ctx.cbrt = ctx._wrap_libmp_function(libmp.mpf_cbrt, libmp.mpc_cbrt)
|
131 |
+
ctx.ln = ctx._wrap_libmp_function(libmp.mpf_log, libmp.mpc_log)
|
132 |
+
ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan)
|
133 |
+
ctx.exp = ctx._wrap_libmp_function(libmp.mpf_exp, libmp.mpc_exp)
|
134 |
+
ctx.expj = ctx._wrap_libmp_function(libmp.mpf_expj, libmp.mpc_expj)
|
135 |
+
ctx.expjpi = ctx._wrap_libmp_function(libmp.mpf_expjpi, libmp.mpc_expjpi)
|
136 |
+
ctx.sin = ctx._wrap_libmp_function(libmp.mpf_sin, libmp.mpc_sin)
|
137 |
+
ctx.cos = ctx._wrap_libmp_function(libmp.mpf_cos, libmp.mpc_cos)
|
138 |
+
ctx.tan = ctx._wrap_libmp_function(libmp.mpf_tan, libmp.mpc_tan)
|
139 |
+
ctx.sinh = ctx._wrap_libmp_function(libmp.mpf_sinh, libmp.mpc_sinh)
|
140 |
+
ctx.cosh = ctx._wrap_libmp_function(libmp.mpf_cosh, libmp.mpc_cosh)
|
141 |
+
ctx.tanh = ctx._wrap_libmp_function(libmp.mpf_tanh, libmp.mpc_tanh)
|
142 |
+
ctx.asin = ctx._wrap_libmp_function(libmp.mpf_asin, libmp.mpc_asin)
|
143 |
+
ctx.acos = ctx._wrap_libmp_function(libmp.mpf_acos, libmp.mpc_acos)
|
144 |
+
ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan)
|
145 |
+
ctx.asinh = ctx._wrap_libmp_function(libmp.mpf_asinh, libmp.mpc_asinh)
|
146 |
+
ctx.acosh = ctx._wrap_libmp_function(libmp.mpf_acosh, libmp.mpc_acosh)
|
147 |
+
ctx.atanh = ctx._wrap_libmp_function(libmp.mpf_atanh, libmp.mpc_atanh)
|
148 |
+
ctx.sinpi = ctx._wrap_libmp_function(libmp.mpf_sin_pi, libmp.mpc_sin_pi)
|
149 |
+
ctx.cospi = ctx._wrap_libmp_function(libmp.mpf_cos_pi, libmp.mpc_cos_pi)
|
150 |
+
ctx.floor = ctx._wrap_libmp_function(libmp.mpf_floor, libmp.mpc_floor)
|
151 |
+
ctx.ceil = ctx._wrap_libmp_function(libmp.mpf_ceil, libmp.mpc_ceil)
|
152 |
+
ctx.nint = ctx._wrap_libmp_function(libmp.mpf_nint, libmp.mpc_nint)
|
153 |
+
ctx.frac = ctx._wrap_libmp_function(libmp.mpf_frac, libmp.mpc_frac)
|
154 |
+
ctx.fib = ctx.fibonacci = ctx._wrap_libmp_function(libmp.mpf_fibonacci, libmp.mpc_fibonacci)
|
155 |
+
|
156 |
+
ctx.gamma = ctx._wrap_libmp_function(libmp.mpf_gamma, libmp.mpc_gamma)
|
157 |
+
ctx.rgamma = ctx._wrap_libmp_function(libmp.mpf_rgamma, libmp.mpc_rgamma)
|
158 |
+
ctx.loggamma = ctx._wrap_libmp_function(libmp.mpf_loggamma, libmp.mpc_loggamma)
|
159 |
+
ctx.fac = ctx.factorial = ctx._wrap_libmp_function(libmp.mpf_factorial, libmp.mpc_factorial)
|
160 |
+
|
161 |
+
ctx.digamma = ctx._wrap_libmp_function(libmp.mpf_psi0, libmp.mpc_psi0)
|
162 |
+
ctx.harmonic = ctx._wrap_libmp_function(libmp.mpf_harmonic, libmp.mpc_harmonic)
|
163 |
+
ctx.ei = ctx._wrap_libmp_function(libmp.mpf_ei, libmp.mpc_ei)
|
164 |
+
ctx.e1 = ctx._wrap_libmp_function(libmp.mpf_e1, libmp.mpc_e1)
|
165 |
+
ctx._ci = ctx._wrap_libmp_function(libmp.mpf_ci, libmp.mpc_ci)
|
166 |
+
ctx._si = ctx._wrap_libmp_function(libmp.mpf_si, libmp.mpc_si)
|
167 |
+
ctx.ellipk = ctx._wrap_libmp_function(libmp.mpf_ellipk, libmp.mpc_ellipk)
|
168 |
+
ctx._ellipe = ctx._wrap_libmp_function(libmp.mpf_ellipe, libmp.mpc_ellipe)
|
169 |
+
ctx.agm1 = ctx._wrap_libmp_function(libmp.mpf_agm1, libmp.mpc_agm1)
|
170 |
+
ctx._erf = ctx._wrap_libmp_function(libmp.mpf_erf, None)
|
171 |
+
ctx._erfc = ctx._wrap_libmp_function(libmp.mpf_erfc, None)
|
172 |
+
ctx._zeta = ctx._wrap_libmp_function(libmp.mpf_zeta, libmp.mpc_zeta)
|
173 |
+
ctx._altzeta = ctx._wrap_libmp_function(libmp.mpf_altzeta, libmp.mpc_altzeta)
|
174 |
+
|
175 |
+
# Faster versions
|
176 |
+
ctx.sqrt = getattr(ctx, "_sage_sqrt", ctx.sqrt)
|
177 |
+
ctx.exp = getattr(ctx, "_sage_exp", ctx.exp)
|
178 |
+
ctx.ln = getattr(ctx, "_sage_ln", ctx.ln)
|
179 |
+
ctx.cos = getattr(ctx, "_sage_cos", ctx.cos)
|
180 |
+
ctx.sin = getattr(ctx, "_sage_sin", ctx.sin)
|
181 |
+
|
182 |
+
def to_fixed(ctx, x, prec):
|
183 |
+
return x.to_fixed(prec)
|
184 |
+
|
185 |
+
def hypot(ctx, x, y):
|
186 |
+
r"""
|
187 |
+
Computes the Euclidean norm of the vector `(x, y)`, equal
|
188 |
+
to `\sqrt{x^2 + y^2}`. Both `x` and `y` must be real."""
|
189 |
+
x = ctx.convert(x)
|
190 |
+
y = ctx.convert(y)
|
191 |
+
return ctx.make_mpf(libmp.mpf_hypot(x._mpf_, y._mpf_, *ctx._prec_rounding))
|
192 |
+
|
193 |
+
def _gamma_upper_int(ctx, n, z):
|
194 |
+
n = int(ctx._re(n))
|
195 |
+
if n == 0:
|
196 |
+
return ctx.e1(z)
|
197 |
+
if not hasattr(z, '_mpf_'):
|
198 |
+
raise NotImplementedError
|
199 |
+
prec, rounding = ctx._prec_rounding
|
200 |
+
real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding, gamma=True)
|
201 |
+
if imag is None:
|
202 |
+
return ctx.make_mpf(real)
|
203 |
+
else:
|
204 |
+
return ctx.make_mpc((real, imag))
|
205 |
+
|
206 |
+
def _expint_int(ctx, n, z):
|
207 |
+
n = int(n)
|
208 |
+
if n == 1:
|
209 |
+
return ctx.e1(z)
|
210 |
+
if not hasattr(z, '_mpf_'):
|
211 |
+
raise NotImplementedError
|
212 |
+
prec, rounding = ctx._prec_rounding
|
213 |
+
real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding)
|
214 |
+
if imag is None:
|
215 |
+
return ctx.make_mpf(real)
|
216 |
+
else:
|
217 |
+
return ctx.make_mpc((real, imag))
|
218 |
+
|
219 |
+
def _nthroot(ctx, x, n):
|
220 |
+
if hasattr(x, '_mpf_'):
|
221 |
+
try:
|
222 |
+
return ctx.make_mpf(libmp.mpf_nthroot(x._mpf_, n, *ctx._prec_rounding))
|
223 |
+
except ComplexResult:
|
224 |
+
if ctx.trap_complex:
|
225 |
+
raise
|
226 |
+
x = (x._mpf_, libmp.fzero)
|
227 |
+
else:
|
228 |
+
x = x._mpc_
|
229 |
+
return ctx.make_mpc(libmp.mpc_nthroot(x, n, *ctx._prec_rounding))
|
230 |
+
|
231 |
+
def _besselj(ctx, n, z):
|
232 |
+
prec, rounding = ctx._prec_rounding
|
233 |
+
if hasattr(z, '_mpf_'):
|
234 |
+
return ctx.make_mpf(libmp.mpf_besseljn(n, z._mpf_, prec, rounding))
|
235 |
+
elif hasattr(z, '_mpc_'):
|
236 |
+
return ctx.make_mpc(libmp.mpc_besseljn(n, z._mpc_, prec, rounding))
|
237 |
+
|
238 |
+
def _agm(ctx, a, b=1):
|
239 |
+
prec, rounding = ctx._prec_rounding
|
240 |
+
if hasattr(a, '_mpf_') and hasattr(b, '_mpf_'):
|
241 |
+
try:
|
242 |
+
v = libmp.mpf_agm(a._mpf_, b._mpf_, prec, rounding)
|
243 |
+
return ctx.make_mpf(v)
|
244 |
+
except ComplexResult:
|
245 |
+
pass
|
246 |
+
if hasattr(a, '_mpf_'): a = (a._mpf_, libmp.fzero)
|
247 |
+
else: a = a._mpc_
|
248 |
+
if hasattr(b, '_mpf_'): b = (b._mpf_, libmp.fzero)
|
249 |
+
else: b = b._mpc_
|
250 |
+
return ctx.make_mpc(libmp.mpc_agm(a, b, prec, rounding))
|
251 |
+
|
252 |
+
def bernoulli(ctx, n):
|
253 |
+
return ctx.make_mpf(libmp.mpf_bernoulli(int(n), *ctx._prec_rounding))
|
254 |
+
|
255 |
+
def _zeta_int(ctx, n):
|
256 |
+
return ctx.make_mpf(libmp.mpf_zeta_int(int(n), *ctx._prec_rounding))
|
257 |
+
|
258 |
+
def atan2(ctx, y, x):
|
259 |
+
x = ctx.convert(x)
|
260 |
+
y = ctx.convert(y)
|
261 |
+
return ctx.make_mpf(libmp.mpf_atan2(y._mpf_, x._mpf_, *ctx._prec_rounding))
|
262 |
+
|
263 |
+
def psi(ctx, m, z):
|
264 |
+
z = ctx.convert(z)
|
265 |
+
m = int(m)
|
266 |
+
if ctx._is_real_type(z):
|
267 |
+
return ctx.make_mpf(libmp.mpf_psi(m, z._mpf_, *ctx._prec_rounding))
|
268 |
+
else:
|
269 |
+
return ctx.make_mpc(libmp.mpc_psi(m, z._mpc_, *ctx._prec_rounding))
|
270 |
+
|
271 |
+
def cos_sin(ctx, x, **kwargs):
|
272 |
+
if type(x) not in ctx.types:
|
273 |
+
x = ctx.convert(x)
|
274 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
275 |
+
if hasattr(x, '_mpf_'):
|
276 |
+
c, s = libmp.mpf_cos_sin(x._mpf_, prec, rounding)
|
277 |
+
return ctx.make_mpf(c), ctx.make_mpf(s)
|
278 |
+
elif hasattr(x, '_mpc_'):
|
279 |
+
c, s = libmp.mpc_cos_sin(x._mpc_, prec, rounding)
|
280 |
+
return ctx.make_mpc(c), ctx.make_mpc(s)
|
281 |
+
else:
|
282 |
+
return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs)
|
283 |
+
|
284 |
+
def cospi_sinpi(ctx, x, **kwargs):
|
285 |
+
if type(x) not in ctx.types:
|
286 |
+
x = ctx.convert(x)
|
287 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
288 |
+
if hasattr(x, '_mpf_'):
|
289 |
+
c, s = libmp.mpf_cos_sin_pi(x._mpf_, prec, rounding)
|
290 |
+
return ctx.make_mpf(c), ctx.make_mpf(s)
|
291 |
+
elif hasattr(x, '_mpc_'):
|
292 |
+
c, s = libmp.mpc_cos_sin_pi(x._mpc_, prec, rounding)
|
293 |
+
return ctx.make_mpc(c), ctx.make_mpc(s)
|
294 |
+
else:
|
295 |
+
return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs)
|
296 |
+
|
297 |
+
def clone(ctx):
|
298 |
+
"""
|
299 |
+
Create a copy of the context, with the same working precision.
|
300 |
+
"""
|
301 |
+
a = ctx.__class__()
|
302 |
+
a.prec = ctx.prec
|
303 |
+
return a
|
304 |
+
|
305 |
+
# Several helper methods
|
306 |
+
# TODO: add more of these, make consistent, write docstrings, ...
|
307 |
+
|
308 |
+
def _is_real_type(ctx, x):
|
309 |
+
if hasattr(x, '_mpc_') or type(x) is complex:
|
310 |
+
return False
|
311 |
+
return True
|
312 |
+
|
313 |
+
def _is_complex_type(ctx, x):
|
314 |
+
if hasattr(x, '_mpc_') or type(x) is complex:
|
315 |
+
return True
|
316 |
+
return False
|
317 |
+
|
318 |
+
def isnan(ctx, x):
|
319 |
+
"""
|
320 |
+
Return *True* if *x* is a NaN (not-a-number), or for a complex
|
321 |
+
number, whether either the real or complex part is NaN;
|
322 |
+
otherwise return *False*::
|
323 |
+
|
324 |
+
>>> from mpmath import *
|
325 |
+
>>> isnan(3.14)
|
326 |
+
False
|
327 |
+
>>> isnan(nan)
|
328 |
+
True
|
329 |
+
>>> isnan(mpc(3.14,2.72))
|
330 |
+
False
|
331 |
+
>>> isnan(mpc(3.14,nan))
|
332 |
+
True
|
333 |
+
|
334 |
+
"""
|
335 |
+
if hasattr(x, "_mpf_"):
|
336 |
+
return x._mpf_ == fnan
|
337 |
+
if hasattr(x, "_mpc_"):
|
338 |
+
return fnan in x._mpc_
|
339 |
+
if isinstance(x, int_types) or isinstance(x, rational.mpq):
|
340 |
+
return False
|
341 |
+
x = ctx.convert(x)
|
342 |
+
if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):
|
343 |
+
return ctx.isnan(x)
|
344 |
+
raise TypeError("isnan() needs a number as input")
|
345 |
+
|
346 |
+
def isfinite(ctx, x):
|
347 |
+
"""
|
348 |
+
Return *True* if *x* is a finite number, i.e. neither
|
349 |
+
an infinity or a NaN.
|
350 |
+
|
351 |
+
>>> from mpmath import *
|
352 |
+
>>> isfinite(inf)
|
353 |
+
False
|
354 |
+
>>> isfinite(-inf)
|
355 |
+
False
|
356 |
+
>>> isfinite(3)
|
357 |
+
True
|
358 |
+
>>> isfinite(nan)
|
359 |
+
False
|
360 |
+
>>> isfinite(3+4j)
|
361 |
+
True
|
362 |
+
>>> isfinite(mpc(3,inf))
|
363 |
+
False
|
364 |
+
>>> isfinite(mpc(nan,3))
|
365 |
+
False
|
366 |
+
|
367 |
+
"""
|
368 |
+
if ctx.isinf(x) or ctx.isnan(x):
|
369 |
+
return False
|
370 |
+
return True
|
371 |
+
|
372 |
+
def isnpint(ctx, x):
|
373 |
+
"""
|
374 |
+
Determine if *x* is a nonpositive integer.
|
375 |
+
"""
|
376 |
+
if not x:
|
377 |
+
return True
|
378 |
+
if hasattr(x, '_mpf_'):
|
379 |
+
sign, man, exp, bc = x._mpf_
|
380 |
+
return sign and exp >= 0
|
381 |
+
if hasattr(x, '_mpc_'):
|
382 |
+
return not x.imag and ctx.isnpint(x.real)
|
383 |
+
if type(x) in int_types:
|
384 |
+
return x <= 0
|
385 |
+
if isinstance(x, ctx.mpq):
|
386 |
+
p, q = x._mpq_
|
387 |
+
if not p:
|
388 |
+
return True
|
389 |
+
return q == 1 and p <= 0
|
390 |
+
return ctx.isnpint(ctx.convert(x))
|
391 |
+
|
392 |
+
def __str__(ctx):
|
393 |
+
lines = ["Mpmath settings:",
|
394 |
+
(" mp.prec = %s" % ctx.prec).ljust(30) + "[default: 53]",
|
395 |
+
(" mp.dps = %s" % ctx.dps).ljust(30) + "[default: 15]",
|
396 |
+
(" mp.trap_complex = %s" % ctx.trap_complex).ljust(30) + "[default: False]",
|
397 |
+
]
|
398 |
+
return "\n".join(lines)
|
399 |
+
|
400 |
+
@property
|
401 |
+
def _repr_digits(ctx):
|
402 |
+
return repr_dps(ctx._prec)
|
403 |
+
|
404 |
+
@property
|
405 |
+
def _str_digits(ctx):
|
406 |
+
return ctx._dps
|
407 |
+
|
408 |
+
def extraprec(ctx, n, normalize_output=False):
|
409 |
+
"""
|
410 |
+
The block
|
411 |
+
|
412 |
+
with extraprec(n):
|
413 |
+
<code>
|
414 |
+
|
415 |
+
increases the precision n bits, executes <code>, and then
|
416 |
+
restores the precision.
|
417 |
+
|
418 |
+
extraprec(n)(f) returns a decorated version of the function f
|
419 |
+
that increases the working precision by n bits before execution,
|
420 |
+
and restores the parent precision afterwards. With
|
421 |
+
normalize_output=True, it rounds the return value to the parent
|
422 |
+
precision.
|
423 |
+
"""
|
424 |
+
return PrecisionManager(ctx, lambda p: p + n, None, normalize_output)
|
425 |
+
|
426 |
+
def extradps(ctx, n, normalize_output=False):
|
427 |
+
"""
|
428 |
+
This function is analogous to extraprec (see documentation)
|
429 |
+
but changes the decimal precision instead of the number of bits.
|
430 |
+
"""
|
431 |
+
return PrecisionManager(ctx, None, lambda d: d + n, normalize_output)
|
432 |
+
|
433 |
+
def workprec(ctx, n, normalize_output=False):
|
434 |
+
"""
|
435 |
+
The block
|
436 |
+
|
437 |
+
with workprec(n):
|
438 |
+
<code>
|
439 |
+
|
440 |
+
sets the precision to n bits, executes <code>, and then restores
|
441 |
+
the precision.
|
442 |
+
|
443 |
+
workprec(n)(f) returns a decorated version of the function f
|
444 |
+
that sets the precision to n bits before execution,
|
445 |
+
and restores the precision afterwards. With normalize_output=True,
|
446 |
+
it rounds the return value to the parent precision.
|
447 |
+
"""
|
448 |
+
return PrecisionManager(ctx, lambda p: n, None, normalize_output)
|
449 |
+
|
450 |
+
def workdps(ctx, n, normalize_output=False):
|
451 |
+
"""
|
452 |
+
This function is analogous to workprec (see documentation)
|
453 |
+
but changes the decimal precision instead of the number of bits.
|
454 |
+
"""
|
455 |
+
return PrecisionManager(ctx, None, lambda d: n, normalize_output)
|
456 |
+
|
457 |
+
def autoprec(ctx, f, maxprec=None, catch=(), verbose=False):
|
458 |
+
r"""
|
459 |
+
Return a wrapped copy of *f* that repeatedly evaluates *f*
|
460 |
+
with increasing precision until the result converges to the
|
461 |
+
full precision used at the point of the call.
|
462 |
+
|
463 |
+
This heuristically protects against rounding errors, at the cost of
|
464 |
+
roughly a 2x slowdown compared to manually setting the optimal
|
465 |
+
precision. This method can, however, easily be fooled if the results
|
466 |
+
from *f* depend "discontinuously" on the precision, for instance
|
467 |
+
if catastrophic cancellation can occur. Therefore, :func:`~mpmath.autoprec`
|
468 |
+
should be used judiciously.
|
469 |
+
|
470 |
+
**Examples**
|
471 |
+
|
472 |
+
Many functions are sensitive to perturbations of the input arguments.
|
473 |
+
If the arguments are decimal numbers, they may have to be converted
|
474 |
+
to binary at a much higher precision. If the amount of required
|
475 |
+
extra precision is unknown, :func:`~mpmath.autoprec` is convenient::
|
476 |
+
|
477 |
+
>>> from mpmath import *
|
478 |
+
>>> mp.dps = 15
|
479 |
+
>>> mp.pretty = True
|
480 |
+
>>> besselj(5, 125 * 10**28) # Exact input
|
481 |
+
-8.03284785591801e-17
|
482 |
+
>>> besselj(5, '1.25e30') # Bad
|
483 |
+
7.12954868316652e-16
|
484 |
+
>>> autoprec(besselj)(5, '1.25e30') # Good
|
485 |
+
-8.03284785591801e-17
|
486 |
+
|
487 |
+
The following fails to converge because `\sin(\pi) = 0` whereas all
|
488 |
+
finite-precision approximations of `\pi` give nonzero values::
|
489 |
+
|
490 |
+
>>> autoprec(sin)(pi) # doctest: +IGNORE_EXCEPTION_DETAIL
|
491 |
+
Traceback (most recent call last):
|
492 |
+
...
|
493 |
+
NoConvergence: autoprec: prec increased to 2910 without convergence
|
494 |
+
|
495 |
+
As the following example shows, :func:`~mpmath.autoprec` can protect against
|
496 |
+
cancellation, but is fooled by too severe cancellation::
|
497 |
+
|
498 |
+
>>> x = 1e-10
|
499 |
+
>>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x)
|
500 |
+
1.00000008274037e-10
|
501 |
+
1.00000000005e-10
|
502 |
+
1.00000000005e-10
|
503 |
+
>>> x = 1e-50
|
504 |
+
>>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x)
|
505 |
+
0.0
|
506 |
+
1.0e-50
|
507 |
+
0.0
|
508 |
+
|
509 |
+
With *catch*, an exception or list of exceptions to intercept
|
510 |
+
may be specified. The raised exception is interpreted
|
511 |
+
as signaling insufficient precision. This permits, for example,
|
512 |
+
evaluating a function where a too low precision results in a
|
513 |
+
division by zero::
|
514 |
+
|
515 |
+
>>> f = lambda x: 1/(exp(x)-1)
|
516 |
+
>>> f(1e-30)
|
517 |
+
Traceback (most recent call last):
|
518 |
+
...
|
519 |
+
ZeroDivisionError
|
520 |
+
>>> autoprec(f, catch=ZeroDivisionError)(1e-30)
|
521 |
+
1.0e+30
|
522 |
+
|
523 |
+
|
524 |
+
"""
|
525 |
+
def f_autoprec_wrapped(*args, **kwargs):
|
526 |
+
prec = ctx.prec
|
527 |
+
if maxprec is None:
|
528 |
+
maxprec2 = ctx._default_hyper_maxprec(prec)
|
529 |
+
else:
|
530 |
+
maxprec2 = maxprec
|
531 |
+
try:
|
532 |
+
ctx.prec = prec + 10
|
533 |
+
try:
|
534 |
+
v1 = f(*args, **kwargs)
|
535 |
+
except catch:
|
536 |
+
v1 = ctx.nan
|
537 |
+
prec2 = prec + 20
|
538 |
+
while 1:
|
539 |
+
ctx.prec = prec2
|
540 |
+
try:
|
541 |
+
v2 = f(*args, **kwargs)
|
542 |
+
except catch:
|
543 |
+
v2 = ctx.nan
|
544 |
+
if v1 == v2:
|
545 |
+
break
|
546 |
+
err = ctx.mag(v2-v1) - ctx.mag(v2)
|
547 |
+
if err < (-prec):
|
548 |
+
break
|
549 |
+
if verbose:
|
550 |
+
print("autoprec: target=%s, prec=%s, accuracy=%s" \
|
551 |
+
% (prec, prec2, -err))
|
552 |
+
v1 = v2
|
553 |
+
if prec2 >= maxprec2:
|
554 |
+
raise ctx.NoConvergence(\
|
555 |
+
"autoprec: prec increased to %i without convergence"\
|
556 |
+
% prec2)
|
557 |
+
prec2 += int(prec2*2)
|
558 |
+
prec2 = min(prec2, maxprec2)
|
559 |
+
finally:
|
560 |
+
ctx.prec = prec
|
561 |
+
return +v2
|
562 |
+
return f_autoprec_wrapped
|
563 |
+
|
564 |
+
def nstr(ctx, x, n=6, **kwargs):
|
565 |
+
"""
|
566 |
+
Convert an ``mpf`` or ``mpc`` to a decimal string literal with *n*
|
567 |
+
significant digits. The small default value for *n* is chosen to
|
568 |
+
make this function useful for printing collections of numbers
|
569 |
+
(lists, matrices, etc).
|
570 |
+
|
571 |
+
If *x* is a list or tuple, :func:`~mpmath.nstr` is applied recursively
|
572 |
+
to each element. For unrecognized classes, :func:`~mpmath.nstr`
|
573 |
+
simply returns ``str(x)``.
|
574 |
+
|
575 |
+
The companion function :func:`~mpmath.nprint` prints the result
|
576 |
+
instead of returning it.
|
577 |
+
|
578 |
+
The keyword arguments *strip_zeros*, *min_fixed*, *max_fixed*
|
579 |
+
and *show_zero_exponent* are forwarded to :func:`~mpmath.libmp.to_str`.
|
580 |
+
|
581 |
+
The number will be printed in fixed-point format if the position
|
582 |
+
of the leading digit is strictly between min_fixed
|
583 |
+
(default = min(-dps/3,-5)) and max_fixed (default = dps).
|
584 |
+
|
585 |
+
To force fixed-point format always, set min_fixed = -inf,
|
586 |
+
max_fixed = +inf. To force floating-point format, set
|
587 |
+
min_fixed >= max_fixed.
|
588 |
+
|
589 |
+
>>> from mpmath import *
|
590 |
+
>>> nstr([+pi, ldexp(1,-500)])
|
591 |
+
'[3.14159, 3.05494e-151]'
|
592 |
+
>>> nprint([+pi, ldexp(1,-500)])
|
593 |
+
[3.14159, 3.05494e-151]
|
594 |
+
>>> nstr(mpf("5e-10"), 5)
|
595 |
+
'5.0e-10'
|
596 |
+
>>> nstr(mpf("5e-10"), 5, strip_zeros=False)
|
597 |
+
'5.0000e-10'
|
598 |
+
>>> nstr(mpf("5e-10"), 5, strip_zeros=False, min_fixed=-11)
|
599 |
+
'0.00000000050000'
|
600 |
+
>>> nstr(mpf(0), 5, show_zero_exponent=True)
|
601 |
+
'0.0e+0'
|
602 |
+
|
603 |
+
"""
|
604 |
+
if isinstance(x, list):
|
605 |
+
return "[%s]" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x))
|
606 |
+
if isinstance(x, tuple):
|
607 |
+
return "(%s)" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x))
|
608 |
+
if hasattr(x, '_mpf_'):
|
609 |
+
return to_str(x._mpf_, n, **kwargs)
|
610 |
+
if hasattr(x, '_mpc_'):
|
611 |
+
return "(" + mpc_to_str(x._mpc_, n, **kwargs) + ")"
|
612 |
+
if isinstance(x, basestring):
|
613 |
+
return repr(x)
|
614 |
+
if isinstance(x, ctx.matrix):
|
615 |
+
return x.__nstr__(n, **kwargs)
|
616 |
+
return str(x)
|
617 |
+
|
618 |
+
def _convert_fallback(ctx, x, strings):
|
619 |
+
if strings and isinstance(x, basestring):
|
620 |
+
if 'j' in x.lower():
|
621 |
+
x = x.lower().replace(' ', '')
|
622 |
+
match = get_complex.match(x)
|
623 |
+
re = match.group('re')
|
624 |
+
if not re:
|
625 |
+
re = 0
|
626 |
+
im = match.group('im').rstrip('j')
|
627 |
+
return ctx.mpc(ctx.convert(re), ctx.convert(im))
|
628 |
+
if hasattr(x, "_mpi_"):
|
629 |
+
a, b = x._mpi_
|
630 |
+
if a == b:
|
631 |
+
return ctx.make_mpf(a)
|
632 |
+
else:
|
633 |
+
raise ValueError("can only create mpf from zero-width interval")
|
634 |
+
raise TypeError("cannot create mpf from " + repr(x))
|
635 |
+
|
636 |
+
def mpmathify(ctx, *args, **kwargs):
|
637 |
+
return ctx.convert(*args, **kwargs)
|
638 |
+
|
639 |
+
def _parse_prec(ctx, kwargs):
|
640 |
+
if kwargs:
|
641 |
+
if kwargs.get('exact'):
|
642 |
+
return 0, 'f'
|
643 |
+
prec, rounding = ctx._prec_rounding
|
644 |
+
if 'rounding' in kwargs:
|
645 |
+
rounding = kwargs['rounding']
|
646 |
+
if 'prec' in kwargs:
|
647 |
+
prec = kwargs['prec']
|
648 |
+
if prec == ctx.inf:
|
649 |
+
return 0, 'f'
|
650 |
+
else:
|
651 |
+
prec = int(prec)
|
652 |
+
elif 'dps' in kwargs:
|
653 |
+
dps = kwargs['dps']
|
654 |
+
if dps == ctx.inf:
|
655 |
+
return 0, 'f'
|
656 |
+
prec = dps_to_prec(dps)
|
657 |
+
return prec, rounding
|
658 |
+
return ctx._prec_rounding
|
659 |
+
|
660 |
+
_exact_overflow_msg = "the exact result does not fit in memory"
|
661 |
+
|
662 |
+
_hypsum_msg = """hypsum() failed to converge to the requested %i bits of accuracy
|
663 |
+
using a working precision of %i bits. Try with a higher maxprec,
|
664 |
+
maxterms, or set zeroprec."""
|
665 |
+
|
666 |
+
def hypsum(ctx, p, q, flags, coeffs, z, accurate_small=True, **kwargs):
|
667 |
+
if hasattr(z, "_mpf_"):
|
668 |
+
key = p, q, flags, 'R'
|
669 |
+
v = z._mpf_
|
670 |
+
elif hasattr(z, "_mpc_"):
|
671 |
+
key = p, q, flags, 'C'
|
672 |
+
v = z._mpc_
|
673 |
+
if key not in ctx.hyp_summators:
|
674 |
+
ctx.hyp_summators[key] = libmp.make_hyp_summator(key)[1]
|
675 |
+
summator = ctx.hyp_summators[key]
|
676 |
+
prec = ctx.prec
|
677 |
+
maxprec = kwargs.get('maxprec', ctx._default_hyper_maxprec(prec))
|
678 |
+
extraprec = 50
|
679 |
+
epsshift = 25
|
680 |
+
# Jumps in magnitude occur when parameters are close to negative
|
681 |
+
# integers. We must ensure that these terms are included in
|
682 |
+
# the sum and added accurately
|
683 |
+
magnitude_check = {}
|
684 |
+
max_total_jump = 0
|
685 |
+
for i, c in enumerate(coeffs):
|
686 |
+
if flags[i] == 'Z':
|
687 |
+
if i >= p and c <= 0:
|
688 |
+
ok = False
|
689 |
+
for ii, cc in enumerate(coeffs[:p]):
|
690 |
+
# Note: c <= cc or c < cc, depending on convention
|
691 |
+
if flags[ii] == 'Z' and cc <= 0 and c <= cc:
|
692 |
+
ok = True
|
693 |
+
if not ok:
|
694 |
+
raise ZeroDivisionError("pole in hypergeometric series")
|
695 |
+
continue
|
696 |
+
n, d = ctx.nint_distance(c)
|
697 |
+
n = -int(n)
|
698 |
+
d = -d
|
699 |
+
if i >= p and n >= 0 and d > 4:
|
700 |
+
if n in magnitude_check:
|
701 |
+
magnitude_check[n] += d
|
702 |
+
else:
|
703 |
+
magnitude_check[n] = d
|
704 |
+
extraprec = max(extraprec, d - prec + 60)
|
705 |
+
max_total_jump += abs(d)
|
706 |
+
while 1:
|
707 |
+
if extraprec > maxprec:
|
708 |
+
raise ValueError(ctx._hypsum_msg % (prec, prec+extraprec))
|
709 |
+
wp = prec + extraprec
|
710 |
+
if magnitude_check:
|
711 |
+
mag_dict = dict((n,None) for n in magnitude_check)
|
712 |
+
else:
|
713 |
+
mag_dict = {}
|
714 |
+
zv, have_complex, magnitude = summator(coeffs, v, prec, wp, \
|
715 |
+
epsshift, mag_dict, **kwargs)
|
716 |
+
cancel = -magnitude
|
717 |
+
jumps_resolved = True
|
718 |
+
if extraprec < max_total_jump:
|
719 |
+
for n in mag_dict.values():
|
720 |
+
if (n is None) or (n < prec):
|
721 |
+
jumps_resolved = False
|
722 |
+
break
|
723 |
+
accurate = (cancel < extraprec-25-5 or not accurate_small)
|
724 |
+
if jumps_resolved:
|
725 |
+
if accurate:
|
726 |
+
break
|
727 |
+
# zero?
|
728 |
+
zeroprec = kwargs.get('zeroprec')
|
729 |
+
if zeroprec is not None:
|
730 |
+
if cancel > zeroprec:
|
731 |
+
if have_complex:
|
732 |
+
return ctx.mpc(0)
|
733 |
+
else:
|
734 |
+
return ctx.zero
|
735 |
+
|
736 |
+
# Some near-singularities were not included, so increase
|
737 |
+
# precision and repeat until they are
|
738 |
+
extraprec *= 2
|
739 |
+
# Possible workaround for bad roundoff in fixed-point arithmetic
|
740 |
+
epsshift += 5
|
741 |
+
extraprec += 5
|
742 |
+
|
743 |
+
if type(zv) is tuple:
|
744 |
+
if have_complex:
|
745 |
+
return ctx.make_mpc(zv)
|
746 |
+
else:
|
747 |
+
return ctx.make_mpf(zv)
|
748 |
+
else:
|
749 |
+
return zv
|
750 |
+
|
751 |
+
def ldexp(ctx, x, n):
|
752 |
+
r"""
|
753 |
+
Computes `x 2^n` efficiently. No rounding is performed.
|
754 |
+
The argument `x` must be a real floating-point number (or
|
755 |
+
possible to convert into one) and `n` must be a Python ``int``.
|
756 |
+
|
757 |
+
>>> from mpmath import *
|
758 |
+
>>> mp.dps = 15; mp.pretty = False
|
759 |
+
>>> ldexp(1, 10)
|
760 |
+
mpf('1024.0')
|
761 |
+
>>> ldexp(1, -3)
|
762 |
+
mpf('0.125')
|
763 |
+
|
764 |
+
"""
|
765 |
+
x = ctx.convert(x)
|
766 |
+
return ctx.make_mpf(libmp.mpf_shift(x._mpf_, n))
|
767 |
+
|
768 |
+
def frexp(ctx, x):
|
769 |
+
r"""
|
770 |
+
Given a real number `x`, returns `(y, n)` with `y \in [0.5, 1)`,
|
771 |
+
`n` a Python integer, and such that `x = y 2^n`. No rounding is
|
772 |
+
performed.
|
773 |
+
|
774 |
+
>>> from mpmath import *
|
775 |
+
>>> mp.dps = 15; mp.pretty = False
|
776 |
+
>>> frexp(7.5)
|
777 |
+
(mpf('0.9375'), 3)
|
778 |
+
|
779 |
+
"""
|
780 |
+
x = ctx.convert(x)
|
781 |
+
y, n = libmp.mpf_frexp(x._mpf_)
|
782 |
+
return ctx.make_mpf(y), n
|
783 |
+
|
784 |
+
def fneg(ctx, x, **kwargs):
|
785 |
+
"""
|
786 |
+
Negates the number *x*, giving a floating-point result, optionally
|
787 |
+
using a custom precision and rounding mode.
|
788 |
+
|
789 |
+
See the documentation of :func:`~mpmath.fadd` for a detailed description
|
790 |
+
of how to specify precision and rounding.
|
791 |
+
|
792 |
+
**Examples**
|
793 |
+
|
794 |
+
An mpmath number is returned::
|
795 |
+
|
796 |
+
>>> from mpmath import *
|
797 |
+
>>> mp.dps = 15; mp.pretty = False
|
798 |
+
>>> fneg(2.5)
|
799 |
+
mpf('-2.5')
|
800 |
+
>>> fneg(-5+2j)
|
801 |
+
mpc(real='5.0', imag='-2.0')
|
802 |
+
|
803 |
+
Precise control over rounding is possible::
|
804 |
+
|
805 |
+
>>> x = fadd(2, 1e-100, exact=True)
|
806 |
+
>>> fneg(x)
|
807 |
+
mpf('-2.0')
|
808 |
+
>>> fneg(x, rounding='f')
|
809 |
+
mpf('-2.0000000000000004')
|
810 |
+
|
811 |
+
Negating with and without roundoff::
|
812 |
+
|
813 |
+
>>> n = 200000000000000000000001
|
814 |
+
>>> print(int(-mpf(n)))
|
815 |
+
-200000000000000016777216
|
816 |
+
>>> print(int(fneg(n)))
|
817 |
+
-200000000000000016777216
|
818 |
+
>>> print(int(fneg(n, prec=log(n,2)+1)))
|
819 |
+
-200000000000000000000001
|
820 |
+
>>> print(int(fneg(n, dps=log(n,10)+1)))
|
821 |
+
-200000000000000000000001
|
822 |
+
>>> print(int(fneg(n, prec=inf)))
|
823 |
+
-200000000000000000000001
|
824 |
+
>>> print(int(fneg(n, dps=inf)))
|
825 |
+
-200000000000000000000001
|
826 |
+
>>> print(int(fneg(n, exact=True)))
|
827 |
+
-200000000000000000000001
|
828 |
+
|
829 |
+
"""
|
830 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
831 |
+
x = ctx.convert(x)
|
832 |
+
if hasattr(x, '_mpf_'):
|
833 |
+
return ctx.make_mpf(mpf_neg(x._mpf_, prec, rounding))
|
834 |
+
if hasattr(x, '_mpc_'):
|
835 |
+
return ctx.make_mpc(mpc_neg(x._mpc_, prec, rounding))
|
836 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
837 |
+
|
838 |
+
def fadd(ctx, x, y, **kwargs):
|
839 |
+
"""
|
840 |
+
Adds the numbers *x* and *y*, giving a floating-point result,
|
841 |
+
optionally using a custom precision and rounding mode.
|
842 |
+
|
843 |
+
The default precision is the working precision of the context.
|
844 |
+
You can specify a custom precision in bits by passing the *prec* keyword
|
845 |
+
argument, or by providing an equivalent decimal precision with the *dps*
|
846 |
+
keyword argument. If the precision is set to ``+inf``, or if the flag
|
847 |
+
*exact=True* is passed, an exact addition with no rounding is performed.
|
848 |
+
|
849 |
+
When the precision is finite, the optional *rounding* keyword argument
|
850 |
+
specifies the direction of rounding. Valid options are ``'n'`` for
|
851 |
+
nearest (default), ``'f'`` for floor, ``'c'`` for ceiling, ``'d'``
|
852 |
+
for down, ``'u'`` for up.
|
853 |
+
|
854 |
+
**Examples**
|
855 |
+
|
856 |
+
Using :func:`~mpmath.fadd` with precision and rounding control::
|
857 |
+
|
858 |
+
>>> from mpmath import *
|
859 |
+
>>> mp.dps = 15; mp.pretty = False
|
860 |
+
>>> fadd(2, 1e-20)
|
861 |
+
mpf('2.0')
|
862 |
+
>>> fadd(2, 1e-20, rounding='u')
|
863 |
+
mpf('2.0000000000000004')
|
864 |
+
>>> nprint(fadd(2, 1e-20, prec=100), 25)
|
865 |
+
2.00000000000000000001
|
866 |
+
>>> nprint(fadd(2, 1e-20, dps=15), 25)
|
867 |
+
2.0
|
868 |
+
>>> nprint(fadd(2, 1e-20, dps=25), 25)
|
869 |
+
2.00000000000000000001
|
870 |
+
>>> nprint(fadd(2, 1e-20, exact=True), 25)
|
871 |
+
2.00000000000000000001
|
872 |
+
|
873 |
+
Exact addition avoids cancellation errors, enforcing familiar laws
|
874 |
+
of numbers such as `x+y-x = y`, which don't hold in floating-point
|
875 |
+
arithmetic with finite precision::
|
876 |
+
|
877 |
+
>>> x, y = mpf(2), mpf('1e-1000')
|
878 |
+
>>> print(x + y - x)
|
879 |
+
0.0
|
880 |
+
>>> print(fadd(x, y, prec=inf) - x)
|
881 |
+
1.0e-1000
|
882 |
+
>>> print(fadd(x, y, exact=True) - x)
|
883 |
+
1.0e-1000
|
884 |
+
|
885 |
+
Exact addition can be inefficient and may be impossible to perform
|
886 |
+
with large magnitude differences::
|
887 |
+
|
888 |
+
>>> fadd(1, '1e-100000000000000000000', prec=inf)
|
889 |
+
Traceback (most recent call last):
|
890 |
+
...
|
891 |
+
OverflowError: the exact result does not fit in memory
|
892 |
+
|
893 |
+
"""
|
894 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
895 |
+
x = ctx.convert(x)
|
896 |
+
y = ctx.convert(y)
|
897 |
+
try:
|
898 |
+
if hasattr(x, '_mpf_'):
|
899 |
+
if hasattr(y, '_mpf_'):
|
900 |
+
return ctx.make_mpf(mpf_add(x._mpf_, y._mpf_, prec, rounding))
|
901 |
+
if hasattr(y, '_mpc_'):
|
902 |
+
return ctx.make_mpc(mpc_add_mpf(y._mpc_, x._mpf_, prec, rounding))
|
903 |
+
if hasattr(x, '_mpc_'):
|
904 |
+
if hasattr(y, '_mpf_'):
|
905 |
+
return ctx.make_mpc(mpc_add_mpf(x._mpc_, y._mpf_, prec, rounding))
|
906 |
+
if hasattr(y, '_mpc_'):
|
907 |
+
return ctx.make_mpc(mpc_add(x._mpc_, y._mpc_, prec, rounding))
|
908 |
+
except (ValueError, OverflowError):
|
909 |
+
raise OverflowError(ctx._exact_overflow_msg)
|
910 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
911 |
+
|
912 |
+
def fsub(ctx, x, y, **kwargs):
|
913 |
+
"""
|
914 |
+
Subtracts the numbers *x* and *y*, giving a floating-point result,
|
915 |
+
optionally using a custom precision and rounding mode.
|
916 |
+
|
917 |
+
See the documentation of :func:`~mpmath.fadd` for a detailed description
|
918 |
+
of how to specify precision and rounding.
|
919 |
+
|
920 |
+
**Examples**
|
921 |
+
|
922 |
+
Using :func:`~mpmath.fsub` with precision and rounding control::
|
923 |
+
|
924 |
+
>>> from mpmath import *
|
925 |
+
>>> mp.dps = 15; mp.pretty = False
|
926 |
+
>>> fsub(2, 1e-20)
|
927 |
+
mpf('2.0')
|
928 |
+
>>> fsub(2, 1e-20, rounding='d')
|
929 |
+
mpf('1.9999999999999998')
|
930 |
+
>>> nprint(fsub(2, 1e-20, prec=100), 25)
|
931 |
+
1.99999999999999999999
|
932 |
+
>>> nprint(fsub(2, 1e-20, dps=15), 25)
|
933 |
+
2.0
|
934 |
+
>>> nprint(fsub(2, 1e-20, dps=25), 25)
|
935 |
+
1.99999999999999999999
|
936 |
+
>>> nprint(fsub(2, 1e-20, exact=True), 25)
|
937 |
+
1.99999999999999999999
|
938 |
+
|
939 |
+
Exact subtraction avoids cancellation errors, enforcing familiar laws
|
940 |
+
of numbers such as `x-y+y = x`, which don't hold in floating-point
|
941 |
+
arithmetic with finite precision::
|
942 |
+
|
943 |
+
>>> x, y = mpf(2), mpf('1e1000')
|
944 |
+
>>> print(x - y + y)
|
945 |
+
0.0
|
946 |
+
>>> print(fsub(x, y, prec=inf) + y)
|
947 |
+
2.0
|
948 |
+
>>> print(fsub(x, y, exact=True) + y)
|
949 |
+
2.0
|
950 |
+
|
951 |
+
Exact addition can be inefficient and may be impossible to perform
|
952 |
+
with large magnitude differences::
|
953 |
+
|
954 |
+
>>> fsub(1, '1e-100000000000000000000', prec=inf)
|
955 |
+
Traceback (most recent call last):
|
956 |
+
...
|
957 |
+
OverflowError: the exact result does not fit in memory
|
958 |
+
|
959 |
+
"""
|
960 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
961 |
+
x = ctx.convert(x)
|
962 |
+
y = ctx.convert(y)
|
963 |
+
try:
|
964 |
+
if hasattr(x, '_mpf_'):
|
965 |
+
if hasattr(y, '_mpf_'):
|
966 |
+
return ctx.make_mpf(mpf_sub(x._mpf_, y._mpf_, prec, rounding))
|
967 |
+
if hasattr(y, '_mpc_'):
|
968 |
+
return ctx.make_mpc(mpc_sub((x._mpf_, fzero), y._mpc_, prec, rounding))
|
969 |
+
if hasattr(x, '_mpc_'):
|
970 |
+
if hasattr(y, '_mpf_'):
|
971 |
+
return ctx.make_mpc(mpc_sub_mpf(x._mpc_, y._mpf_, prec, rounding))
|
972 |
+
if hasattr(y, '_mpc_'):
|
973 |
+
return ctx.make_mpc(mpc_sub(x._mpc_, y._mpc_, prec, rounding))
|
974 |
+
except (ValueError, OverflowError):
|
975 |
+
raise OverflowError(ctx._exact_overflow_msg)
|
976 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
977 |
+
|
978 |
+
def fmul(ctx, x, y, **kwargs):
|
979 |
+
"""
|
980 |
+
Multiplies the numbers *x* and *y*, giving a floating-point result,
|
981 |
+
optionally using a custom precision and rounding mode.
|
982 |
+
|
983 |
+
See the documentation of :func:`~mpmath.fadd` for a detailed description
|
984 |
+
of how to specify precision and rounding.
|
985 |
+
|
986 |
+
**Examples**
|
987 |
+
|
988 |
+
The result is an mpmath number::
|
989 |
+
|
990 |
+
>>> from mpmath import *
|
991 |
+
>>> mp.dps = 15; mp.pretty = False
|
992 |
+
>>> fmul(2, 5.0)
|
993 |
+
mpf('10.0')
|
994 |
+
>>> fmul(0.5j, 0.5)
|
995 |
+
mpc(real='0.0', imag='0.25')
|
996 |
+
|
997 |
+
Avoiding roundoff::
|
998 |
+
|
999 |
+
>>> x, y = 10**10+1, 10**15+1
|
1000 |
+
>>> print(x*y)
|
1001 |
+
10000000001000010000000001
|
1002 |
+
>>> print(mpf(x) * mpf(y))
|
1003 |
+
1.0000000001e+25
|
1004 |
+
>>> print(int(mpf(x) * mpf(y)))
|
1005 |
+
10000000001000011026399232
|
1006 |
+
>>> print(int(fmul(x, y)))
|
1007 |
+
10000000001000011026399232
|
1008 |
+
>>> print(int(fmul(x, y, dps=25)))
|
1009 |
+
10000000001000010000000001
|
1010 |
+
>>> print(int(fmul(x, y, exact=True)))
|
1011 |
+
10000000001000010000000001
|
1012 |
+
|
1013 |
+
Exact multiplication with complex numbers can be inefficient and may
|
1014 |
+
be impossible to perform with large magnitude differences between
|
1015 |
+
real and imaginary parts::
|
1016 |
+
|
1017 |
+
>>> x = 1+2j
|
1018 |
+
>>> y = mpc(2, '1e-100000000000000000000')
|
1019 |
+
>>> fmul(x, y)
|
1020 |
+
mpc(real='2.0', imag='4.0')
|
1021 |
+
>>> fmul(x, y, rounding='u')
|
1022 |
+
mpc(real='2.0', imag='4.0000000000000009')
|
1023 |
+
>>> fmul(x, y, exact=True)
|
1024 |
+
Traceback (most recent call last):
|
1025 |
+
...
|
1026 |
+
OverflowError: the exact result does not fit in memory
|
1027 |
+
|
1028 |
+
"""
|
1029 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
1030 |
+
x = ctx.convert(x)
|
1031 |
+
y = ctx.convert(y)
|
1032 |
+
try:
|
1033 |
+
if hasattr(x, '_mpf_'):
|
1034 |
+
if hasattr(y, '_mpf_'):
|
1035 |
+
return ctx.make_mpf(mpf_mul(x._mpf_, y._mpf_, prec, rounding))
|
1036 |
+
if hasattr(y, '_mpc_'):
|
1037 |
+
return ctx.make_mpc(mpc_mul_mpf(y._mpc_, x._mpf_, prec, rounding))
|
1038 |
+
if hasattr(x, '_mpc_'):
|
1039 |
+
if hasattr(y, '_mpf_'):
|
1040 |
+
return ctx.make_mpc(mpc_mul_mpf(x._mpc_, y._mpf_, prec, rounding))
|
1041 |
+
if hasattr(y, '_mpc_'):
|
1042 |
+
return ctx.make_mpc(mpc_mul(x._mpc_, y._mpc_, prec, rounding))
|
1043 |
+
except (ValueError, OverflowError):
|
1044 |
+
raise OverflowError(ctx._exact_overflow_msg)
|
1045 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
1046 |
+
|
1047 |
+
def fdiv(ctx, x, y, **kwargs):
|
1048 |
+
"""
|
1049 |
+
Divides the numbers *x* and *y*, giving a floating-point result,
|
1050 |
+
optionally using a custom precision and rounding mode.
|
1051 |
+
|
1052 |
+
See the documentation of :func:`~mpmath.fadd` for a detailed description
|
1053 |
+
of how to specify precision and rounding.
|
1054 |
+
|
1055 |
+
**Examples**
|
1056 |
+
|
1057 |
+
The result is an mpmath number::
|
1058 |
+
|
1059 |
+
>>> from mpmath import *
|
1060 |
+
>>> mp.dps = 15; mp.pretty = False
|
1061 |
+
>>> fdiv(3, 2)
|
1062 |
+
mpf('1.5')
|
1063 |
+
>>> fdiv(2, 3)
|
1064 |
+
mpf('0.66666666666666663')
|
1065 |
+
>>> fdiv(2+4j, 0.5)
|
1066 |
+
mpc(real='4.0', imag='8.0')
|
1067 |
+
|
1068 |
+
The rounding direction and precision can be controlled::
|
1069 |
+
|
1070 |
+
>>> fdiv(2, 3, dps=3) # Should be accurate to at least 3 digits
|
1071 |
+
mpf('0.6666259765625')
|
1072 |
+
>>> fdiv(2, 3, rounding='d')
|
1073 |
+
mpf('0.66666666666666663')
|
1074 |
+
>>> fdiv(2, 3, prec=60)
|
1075 |
+
mpf('0.66666666666666667')
|
1076 |
+
>>> fdiv(2, 3, rounding='u')
|
1077 |
+
mpf('0.66666666666666674')
|
1078 |
+
|
1079 |
+
Checking the error of a division by performing it at higher precision::
|
1080 |
+
|
1081 |
+
>>> fdiv(2, 3) - fdiv(2, 3, prec=100)
|
1082 |
+
mpf('-3.7007434154172148e-17')
|
1083 |
+
|
1084 |
+
Unlike :func:`~mpmath.fadd`, :func:`~mpmath.fmul`, etc., exact division is not
|
1085 |
+
allowed since the quotient of two floating-point numbers generally
|
1086 |
+
does not have an exact floating-point representation. (In the
|
1087 |
+
future this might be changed to allow the case where the division
|
1088 |
+
is actually exact.)
|
1089 |
+
|
1090 |
+
>>> fdiv(2, 3, exact=True)
|
1091 |
+
Traceback (most recent call last):
|
1092 |
+
...
|
1093 |
+
ValueError: division is not an exact operation
|
1094 |
+
|
1095 |
+
"""
|
1096 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
1097 |
+
if not prec:
|
1098 |
+
raise ValueError("division is not an exact operation")
|
1099 |
+
x = ctx.convert(x)
|
1100 |
+
y = ctx.convert(y)
|
1101 |
+
if hasattr(x, '_mpf_'):
|
1102 |
+
if hasattr(y, '_mpf_'):
|
1103 |
+
return ctx.make_mpf(mpf_div(x._mpf_, y._mpf_, prec, rounding))
|
1104 |
+
if hasattr(y, '_mpc_'):
|
1105 |
+
return ctx.make_mpc(mpc_div((x._mpf_, fzero), y._mpc_, prec, rounding))
|
1106 |
+
if hasattr(x, '_mpc_'):
|
1107 |
+
if hasattr(y, '_mpf_'):
|
1108 |
+
return ctx.make_mpc(mpc_div_mpf(x._mpc_, y._mpf_, prec, rounding))
|
1109 |
+
if hasattr(y, '_mpc_'):
|
1110 |
+
return ctx.make_mpc(mpc_div(x._mpc_, y._mpc_, prec, rounding))
|
1111 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
1112 |
+
|
1113 |
+
def nint_distance(ctx, x):
|
1114 |
+
r"""
|
1115 |
+
Return `(n,d)` where `n` is the nearest integer to `x` and `d` is
|
1116 |
+
an estimate of `\log_2(|x-n|)`. If `d < 0`, `-d` gives the precision
|
1117 |
+
(measured in bits) lost to cancellation when computing `x-n`.
|
1118 |
+
|
1119 |
+
>>> from mpmath import *
|
1120 |
+
>>> n, d = nint_distance(5)
|
1121 |
+
>>> print(n); print(d)
|
1122 |
+
5
|
1123 |
+
-inf
|
1124 |
+
>>> n, d = nint_distance(mpf(5))
|
1125 |
+
>>> print(n); print(d)
|
1126 |
+
5
|
1127 |
+
-inf
|
1128 |
+
>>> n, d = nint_distance(mpf(5.00000001))
|
1129 |
+
>>> print(n); print(d)
|
1130 |
+
5
|
1131 |
+
-26
|
1132 |
+
>>> n, d = nint_distance(mpf(4.99999999))
|
1133 |
+
>>> print(n); print(d)
|
1134 |
+
5
|
1135 |
+
-26
|
1136 |
+
>>> n, d = nint_distance(mpc(5,10))
|
1137 |
+
>>> print(n); print(d)
|
1138 |
+
5
|
1139 |
+
4
|
1140 |
+
>>> n, d = nint_distance(mpc(5,0.000001))
|
1141 |
+
>>> print(n); print(d)
|
1142 |
+
5
|
1143 |
+
-19
|
1144 |
+
|
1145 |
+
"""
|
1146 |
+
typx = type(x)
|
1147 |
+
if typx in int_types:
|
1148 |
+
return int(x), ctx.ninf
|
1149 |
+
elif typx is rational.mpq:
|
1150 |
+
p, q = x._mpq_
|
1151 |
+
n, r = divmod(p, q)
|
1152 |
+
if 2*r >= q:
|
1153 |
+
n += 1
|
1154 |
+
elif not r:
|
1155 |
+
return n, ctx.ninf
|
1156 |
+
# log(p/q-n) = log((p-nq)/q) = log(p-nq) - log(q)
|
1157 |
+
d = bitcount(abs(p-n*q)) - bitcount(q)
|
1158 |
+
return n, d
|
1159 |
+
if hasattr(x, "_mpf_"):
|
1160 |
+
re = x._mpf_
|
1161 |
+
im_dist = ctx.ninf
|
1162 |
+
elif hasattr(x, "_mpc_"):
|
1163 |
+
re, im = x._mpc_
|
1164 |
+
isign, iman, iexp, ibc = im
|
1165 |
+
if iman:
|
1166 |
+
im_dist = iexp + ibc
|
1167 |
+
elif im == fzero:
|
1168 |
+
im_dist = ctx.ninf
|
1169 |
+
else:
|
1170 |
+
raise ValueError("requires a finite number")
|
1171 |
+
else:
|
1172 |
+
x = ctx.convert(x)
|
1173 |
+
if hasattr(x, "_mpf_") or hasattr(x, "_mpc_"):
|
1174 |
+
return ctx.nint_distance(x)
|
1175 |
+
else:
|
1176 |
+
raise TypeError("requires an mpf/mpc")
|
1177 |
+
sign, man, exp, bc = re
|
1178 |
+
mag = exp+bc
|
1179 |
+
# |x| < 0.5
|
1180 |
+
if mag < 0:
|
1181 |
+
n = 0
|
1182 |
+
re_dist = mag
|
1183 |
+
elif man:
|
1184 |
+
# exact integer
|
1185 |
+
if exp >= 0:
|
1186 |
+
n = man << exp
|
1187 |
+
re_dist = ctx.ninf
|
1188 |
+
# exact half-integer
|
1189 |
+
elif exp == -1:
|
1190 |
+
n = (man>>1)+1
|
1191 |
+
re_dist = 0
|
1192 |
+
else:
|
1193 |
+
d = (-exp-1)
|
1194 |
+
t = man >> d
|
1195 |
+
if t & 1:
|
1196 |
+
t += 1
|
1197 |
+
man = (t<<d) - man
|
1198 |
+
else:
|
1199 |
+
man -= (t<<d)
|
1200 |
+
n = t>>1 # int(t)>>1
|
1201 |
+
re_dist = exp+bitcount(man)
|
1202 |
+
if sign:
|
1203 |
+
n = -n
|
1204 |
+
elif re == fzero:
|
1205 |
+
re_dist = ctx.ninf
|
1206 |
+
n = 0
|
1207 |
+
else:
|
1208 |
+
raise ValueError("requires a finite number")
|
1209 |
+
return n, max(re_dist, im_dist)
|
1210 |
+
|
1211 |
+
def fprod(ctx, factors):
|
1212 |
+
r"""
|
1213 |
+
Calculates a product containing a finite number of factors (for
|
1214 |
+
infinite products, see :func:`~mpmath.nprod`). The factors will be
|
1215 |
+
converted to mpmath numbers.
|
1216 |
+
|
1217 |
+
>>> from mpmath import *
|
1218 |
+
>>> mp.dps = 15; mp.pretty = False
|
1219 |
+
>>> fprod([1, 2, 0.5, 7])
|
1220 |
+
mpf('7.0')
|
1221 |
+
|
1222 |
+
"""
|
1223 |
+
orig = ctx.prec
|
1224 |
+
try:
|
1225 |
+
v = ctx.one
|
1226 |
+
for p in factors:
|
1227 |
+
v *= p
|
1228 |
+
finally:
|
1229 |
+
ctx.prec = orig
|
1230 |
+
return +v
|
1231 |
+
|
1232 |
+
def rand(ctx):
|
1233 |
+
"""
|
1234 |
+
Returns an ``mpf`` with value chosen randomly from `[0, 1)`.
|
1235 |
+
The number of randomly generated bits in the mantissa is equal
|
1236 |
+
to the working precision.
|
1237 |
+
"""
|
1238 |
+
return ctx.make_mpf(mpf_rand(ctx._prec))
|
1239 |
+
|
1240 |
+
def fraction(ctx, p, q):
|
1241 |
+
"""
|
1242 |
+
Given Python integers `(p, q)`, returns a lazy ``mpf`` representing
|
1243 |
+
the fraction `p/q`. The value is updated with the precision.
|
1244 |
+
|
1245 |
+
>>> from mpmath import *
|
1246 |
+
>>> mp.dps = 15
|
1247 |
+
>>> a = fraction(1,100)
|
1248 |
+
>>> b = mpf(1)/100
|
1249 |
+
>>> print(a); print(b)
|
1250 |
+
0.01
|
1251 |
+
0.01
|
1252 |
+
>>> mp.dps = 30
|
1253 |
+
>>> print(a); print(b) # a will be accurate
|
1254 |
+
0.01
|
1255 |
+
0.0100000000000000002081668171172
|
1256 |
+
>>> mp.dps = 15
|
1257 |
+
"""
|
1258 |
+
return ctx.constant(lambda prec, rnd: from_rational(p, q, prec, rnd),
|
1259 |
+
'%s/%s' % (p, q))
|
1260 |
+
|
1261 |
+
def absmin(ctx, x):
|
1262 |
+
return abs(ctx.convert(x))
|
1263 |
+
|
1264 |
+
def absmax(ctx, x):
|
1265 |
+
return abs(ctx.convert(x))
|
1266 |
+
|
1267 |
+
def _as_points(ctx, x):
|
1268 |
+
# XXX: remove this?
|
1269 |
+
if hasattr(x, '_mpi_'):
|
1270 |
+
a, b = x._mpi_
|
1271 |
+
return [ctx.make_mpf(a), ctx.make_mpf(b)]
|
1272 |
+
return x
|
1273 |
+
|
1274 |
+
'''
|
1275 |
+
def _zetasum(ctx, s, a, b):
|
1276 |
+
"""
|
1277 |
+
Computes sum of k^(-s) for k = a, a+1, ..., b with a, b both small
|
1278 |
+
integers.
|
1279 |
+
"""
|
1280 |
+
a = int(a)
|
1281 |
+
b = int(b)
|
1282 |
+
s = ctx.convert(s)
|
1283 |
+
prec, rounding = ctx._prec_rounding
|
1284 |
+
if hasattr(s, '_mpf_'):
|
1285 |
+
v = ctx.make_mpf(libmp.mpf_zetasum(s._mpf_, a, b, prec))
|
1286 |
+
elif hasattr(s, '_mpc_'):
|
1287 |
+
v = ctx.make_mpc(libmp.mpc_zetasum(s._mpc_, a, b, prec))
|
1288 |
+
return v
|
1289 |
+
'''
|
1290 |
+
|
1291 |
+
def _zetasum_fast(ctx, s, a, n, derivatives=[0], reflect=False):
|
1292 |
+
if not (ctx.isint(a) and hasattr(s, "_mpc_")):
|
1293 |
+
raise NotImplementedError
|
1294 |
+
a = int(a)
|
1295 |
+
prec = ctx._prec
|
1296 |
+
xs, ys = libmp.mpc_zetasum(s._mpc_, a, n, derivatives, reflect, prec)
|
1297 |
+
xs = [ctx.make_mpc(x) for x in xs]
|
1298 |
+
ys = [ctx.make_mpc(y) for y in ys]
|
1299 |
+
return xs, ys
|
1300 |
+
|
1301 |
+
class PrecisionManager:
|
1302 |
+
def __init__(self, ctx, precfun, dpsfun, normalize_output=False):
|
1303 |
+
self.ctx = ctx
|
1304 |
+
self.precfun = precfun
|
1305 |
+
self.dpsfun = dpsfun
|
1306 |
+
self.normalize_output = normalize_output
|
1307 |
+
def __call__(self, f):
|
1308 |
+
@functools.wraps(f)
|
1309 |
+
def g(*args, **kwargs):
|
1310 |
+
orig = self.ctx.prec
|
1311 |
+
try:
|
1312 |
+
if self.precfun:
|
1313 |
+
self.ctx.prec = self.precfun(self.ctx.prec)
|
1314 |
+
else:
|
1315 |
+
self.ctx.dps = self.dpsfun(self.ctx.dps)
|
1316 |
+
if self.normalize_output:
|
1317 |
+
v = f(*args, **kwargs)
|
1318 |
+
if type(v) is tuple:
|
1319 |
+
return tuple([+a for a in v])
|
1320 |
+
return +v
|
1321 |
+
else:
|
1322 |
+
return f(*args, **kwargs)
|
1323 |
+
finally:
|
1324 |
+
self.ctx.prec = orig
|
1325 |
+
return g
|
1326 |
+
def __enter__(self):
|
1327 |
+
self.origp = self.ctx.prec
|
1328 |
+
if self.precfun:
|
1329 |
+
self.ctx.prec = self.precfun(self.ctx.prec)
|
1330 |
+
else:
|
1331 |
+
self.ctx.dps = self.dpsfun(self.ctx.dps)
|
1332 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
1333 |
+
self.ctx.prec = self.origp
|
1334 |
+
return False
|
1335 |
+
|
1336 |
+
|
1337 |
+
if __name__ == '__main__':
|
1338 |
+
import doctest
|
1339 |
+
doctest.testmod()
|
venv/lib/python3.10/site-packages/mpmath/ctx_mp_python.py
ADDED
@@ -0,0 +1,1149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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floor, round_ceiling, dps_to_prec, round_nearest, prec_to_dps,
|
7 |
+
ComplexResult, to_pickable, from_pickable, normalize,
|
8 |
+
from_int, from_float, from_npfloat, from_Decimal, from_str, to_int, to_float, to_str,
|
9 |
+
from_rational, from_man_exp,
|
10 |
+
fone, fzero, finf, fninf, fnan,
|
11 |
+
mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int,
|
12 |
+
mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod,
|
13 |
+
mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge,
|
14 |
+
mpf_hash, mpf_rand,
|
15 |
+
mpf_sum,
|
16 |
+
bitcount, to_fixed,
|
17 |
+
mpc_to_str,
|
18 |
+
mpc_to_complex, mpc_hash, mpc_pos, mpc_is_nonzero, mpc_neg, mpc_conjugate,
|
19 |
+
mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf,
|
20 |
+
mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int,
|
21 |
+
mpc_mpf_div,
|
22 |
+
mpf_pow,
|
23 |
+
mpf_pi, mpf_degree, mpf_e, mpf_phi, mpf_ln2, mpf_ln10,
|
24 |
+
mpf_euler, mpf_catalan, mpf_apery, mpf_khinchin,
|
25 |
+
mpf_glaisher, mpf_twinprime, mpf_mertens,
|
26 |
+
int_types)
|
27 |
+
|
28 |
+
from . import rational
|
29 |
+
from . import function_docs
|
30 |
+
|
31 |
+
new = object.__new__
|
32 |
+
|
33 |
+
class mpnumeric(object):
|
34 |
+
"""Base class for mpf and mpc."""
|
35 |
+
__slots__ = []
|
36 |
+
def __new__(cls, val):
|
37 |
+
raise NotImplementedError
|
38 |
+
|
39 |
+
class _mpf(mpnumeric):
|
40 |
+
"""
|
41 |
+
An mpf instance holds a real-valued floating-point number. mpf:s
|
42 |
+
work analogously to Python floats, but support arbitrary-precision
|
43 |
+
arithmetic.
|
44 |
+
"""
|
45 |
+
__slots__ = ['_mpf_']
|
46 |
+
|
47 |
+
def __new__(cls, val=fzero, **kwargs):
|
48 |
+
"""A new mpf can be created from a Python float, an int, a
|
49 |
+
or a decimal string representing a number in floating-point
|
50 |
+
format."""
|
51 |
+
prec, rounding = cls.context._prec_rounding
|
52 |
+
if kwargs:
|
53 |
+
prec = kwargs.get('prec', prec)
|
54 |
+
if 'dps' in kwargs:
|
55 |
+
prec = dps_to_prec(kwargs['dps'])
|
56 |
+
rounding = kwargs.get('rounding', rounding)
|
57 |
+
if type(val) is cls:
|
58 |
+
sign, man, exp, bc = val._mpf_
|
59 |
+
if (not man) and exp:
|
60 |
+
return val
|
61 |
+
v = new(cls)
|
62 |
+
v._mpf_ = normalize(sign, man, exp, bc, prec, rounding)
|
63 |
+
return v
|
64 |
+
elif type(val) is tuple:
|
65 |
+
if len(val) == 2:
|
66 |
+
v = new(cls)
|
67 |
+
v._mpf_ = from_man_exp(val[0], val[1], prec, rounding)
|
68 |
+
return v
|
69 |
+
if len(val) == 4:
|
70 |
+
if val not in (finf, fninf, fnan):
|
71 |
+
sign, man, exp, bc = val
|
72 |
+
val = normalize(sign, MPZ(man), exp, bc, prec, rounding)
|
73 |
+
v = new(cls)
|
74 |
+
v._mpf_ = val
|
75 |
+
return v
|
76 |
+
raise ValueError
|
77 |
+
else:
|
78 |
+
v = new(cls)
|
79 |
+
v._mpf_ = mpf_pos(cls.mpf_convert_arg(val, prec, rounding), prec, rounding)
|
80 |
+
return v
|
81 |
+
|
82 |
+
@classmethod
|
83 |
+
def mpf_convert_arg(cls, x, prec, rounding):
|
84 |
+
if isinstance(x, int_types): return from_int(x)
|
85 |
+
if isinstance(x, float): return from_float(x)
|
86 |
+
if isinstance(x, basestring): return from_str(x, prec, rounding)
|
87 |
+
if isinstance(x, cls.context.constant): return x.func(prec, rounding)
|
88 |
+
if hasattr(x, '_mpf_'): return x._mpf_
|
89 |
+
if hasattr(x, '_mpmath_'):
|
90 |
+
t = cls.context.convert(x._mpmath_(prec, rounding))
|
91 |
+
if hasattr(t, '_mpf_'):
|
92 |
+
return t._mpf_
|
93 |
+
if hasattr(x, '_mpi_'):
|
94 |
+
a, b = x._mpi_
|
95 |
+
if a == b:
|
96 |
+
return a
|
97 |
+
raise ValueError("can only create mpf from zero-width interval")
|
98 |
+
raise TypeError("cannot create mpf from " + repr(x))
|
99 |
+
|
100 |
+
@classmethod
|
101 |
+
def mpf_convert_rhs(cls, x):
|
102 |
+
if isinstance(x, int_types): return from_int(x)
|
103 |
+
if isinstance(x, float): return from_float(x)
|
104 |
+
if isinstance(x, complex_types): return cls.context.mpc(x)
|
105 |
+
if isinstance(x, rational.mpq):
|
106 |
+
p, q = x._mpq_
|
107 |
+
return from_rational(p, q, cls.context.prec)
|
108 |
+
if hasattr(x, '_mpf_'): return x._mpf_
|
109 |
+
if hasattr(x, '_mpmath_'):
|
110 |
+
t = cls.context.convert(x._mpmath_(*cls.context._prec_rounding))
|
111 |
+
if hasattr(t, '_mpf_'):
|
112 |
+
return t._mpf_
|
113 |
+
return t
|
114 |
+
return NotImplemented
|
115 |
+
|
116 |
+
@classmethod
|
117 |
+
def mpf_convert_lhs(cls, x):
|
118 |
+
x = cls.mpf_convert_rhs(x)
|
119 |
+
if type(x) is tuple:
|
120 |
+
return cls.context.make_mpf(x)
|
121 |
+
return x
|
122 |
+
|
123 |
+
man_exp = property(lambda self: self._mpf_[1:3])
|
124 |
+
man = property(lambda self: self._mpf_[1])
|
125 |
+
exp = property(lambda self: self._mpf_[2])
|
126 |
+
bc = property(lambda self: self._mpf_[3])
|
127 |
+
|
128 |
+
real = property(lambda self: self)
|
129 |
+
imag = property(lambda self: self.context.zero)
|
130 |
+
|
131 |
+
conjugate = lambda self: self
|
132 |
+
|
133 |
+
def __getstate__(self): return to_pickable(self._mpf_)
|
134 |
+
def __setstate__(self, val): self._mpf_ = from_pickable(val)
|
135 |
+
|
136 |
+
def __repr__(s):
|
137 |
+
if s.context.pretty:
|
138 |
+
return str(s)
|
139 |
+
return "mpf('%s')" % to_str(s._mpf_, s.context._repr_digits)
|
140 |
+
|
141 |
+
def __str__(s): return to_str(s._mpf_, s.context._str_digits)
|
142 |
+
def __hash__(s): return mpf_hash(s._mpf_)
|
143 |
+
def __int__(s): return int(to_int(s._mpf_))
|
144 |
+
def __long__(s): return long(to_int(s._mpf_))
|
145 |
+
def __float__(s): return to_float(s._mpf_, rnd=s.context._prec_rounding[1])
|
146 |
+
def __complex__(s): return complex(float(s))
|
147 |
+
def __nonzero__(s): return s._mpf_ != fzero
|
148 |
+
|
149 |
+
__bool__ = __nonzero__
|
150 |
+
|
151 |
+
def __abs__(s):
|
152 |
+
cls, new, (prec, rounding) = s._ctxdata
|
153 |
+
v = new(cls)
|
154 |
+
v._mpf_ = mpf_abs(s._mpf_, prec, rounding)
|
155 |
+
return v
|
156 |
+
|
157 |
+
def __pos__(s):
|
158 |
+
cls, new, (prec, rounding) = s._ctxdata
|
159 |
+
v = new(cls)
|
160 |
+
v._mpf_ = mpf_pos(s._mpf_, prec, rounding)
|
161 |
+
return v
|
162 |
+
|
163 |
+
def __neg__(s):
|
164 |
+
cls, new, (prec, rounding) = s._ctxdata
|
165 |
+
v = new(cls)
|
166 |
+
v._mpf_ = mpf_neg(s._mpf_, prec, rounding)
|
167 |
+
return v
|
168 |
+
|
169 |
+
def _cmp(s, t, func):
|
170 |
+
if hasattr(t, '_mpf_'):
|
171 |
+
t = t._mpf_
|
172 |
+
else:
|
173 |
+
t = s.mpf_convert_rhs(t)
|
174 |
+
if t is NotImplemented:
|
175 |
+
return t
|
176 |
+
return func(s._mpf_, t)
|
177 |
+
|
178 |
+
def __cmp__(s, t): return s._cmp(t, mpf_cmp)
|
179 |
+
def __lt__(s, t): return s._cmp(t, mpf_lt)
|
180 |
+
def __gt__(s, t): return s._cmp(t, mpf_gt)
|
181 |
+
def __le__(s, t): return s._cmp(t, mpf_le)
|
182 |
+
def __ge__(s, t): return s._cmp(t, mpf_ge)
|
183 |
+
|
184 |
+
def __ne__(s, t):
|
185 |
+
v = s.__eq__(t)
|
186 |
+
if v is NotImplemented:
|
187 |
+
return v
|
188 |
+
return not v
|
189 |
+
|
190 |
+
def __rsub__(s, t):
|
191 |
+
cls, new, (prec, rounding) = s._ctxdata
|
192 |
+
if type(t) in int_types:
|
193 |
+
v = new(cls)
|
194 |
+
v._mpf_ = mpf_sub(from_int(t), s._mpf_, prec, rounding)
|
195 |
+
return v
|
196 |
+
t = s.mpf_convert_lhs(t)
|
197 |
+
if t is NotImplemented:
|
198 |
+
return t
|
199 |
+
return t - s
|
200 |
+
|
201 |
+
def __rdiv__(s, t):
|
202 |
+
cls, new, (prec, rounding) = s._ctxdata
|
203 |
+
if isinstance(t, int_types):
|
204 |
+
v = new(cls)
|
205 |
+
v._mpf_ = mpf_rdiv_int(t, s._mpf_, prec, rounding)
|
206 |
+
return v
|
207 |
+
t = s.mpf_convert_lhs(t)
|
208 |
+
if t is NotImplemented:
|
209 |
+
return t
|
210 |
+
return t / s
|
211 |
+
|
212 |
+
def __rpow__(s, t):
|
213 |
+
t = s.mpf_convert_lhs(t)
|
214 |
+
if t is NotImplemented:
|
215 |
+
return t
|
216 |
+
return t ** s
|
217 |
+
|
218 |
+
def __rmod__(s, t):
|
219 |
+
t = s.mpf_convert_lhs(t)
|
220 |
+
if t is NotImplemented:
|
221 |
+
return t
|
222 |
+
return t % s
|
223 |
+
|
224 |
+
def sqrt(s):
|
225 |
+
return s.context.sqrt(s)
|
226 |
+
|
227 |
+
def ae(s, t, rel_eps=None, abs_eps=None):
|
228 |
+
return s.context.almosteq(s, t, rel_eps, abs_eps)
|
229 |
+
|
230 |
+
def to_fixed(self, prec):
|
231 |
+
return to_fixed(self._mpf_, prec)
|
232 |
+
|
233 |
+
def __round__(self, *args):
|
234 |
+
return round(float(self), *args)
|
235 |
+
|
236 |
+
mpf_binary_op = """
|
237 |
+
def %NAME%(self, other):
|
238 |
+
mpf, new, (prec, rounding) = self._ctxdata
|
239 |
+
sval = self._mpf_
|
240 |
+
if hasattr(other, '_mpf_'):
|
241 |
+
tval = other._mpf_
|
242 |
+
%WITH_MPF%
|
243 |
+
ttype = type(other)
|
244 |
+
if ttype in int_types:
|
245 |
+
%WITH_INT%
|
246 |
+
elif ttype is float:
|
247 |
+
tval = from_float(other)
|
248 |
+
%WITH_MPF%
|
249 |
+
elif hasattr(other, '_mpc_'):
|
250 |
+
tval = other._mpc_
|
251 |
+
mpc = type(other)
|
252 |
+
%WITH_MPC%
|
253 |
+
elif ttype is complex:
|
254 |
+
tval = from_float(other.real), from_float(other.imag)
|
255 |
+
mpc = self.context.mpc
|
256 |
+
%WITH_MPC%
|
257 |
+
if isinstance(other, mpnumeric):
|
258 |
+
return NotImplemented
|
259 |
+
try:
|
260 |
+
other = mpf.context.convert(other, strings=False)
|
261 |
+
except TypeError:
|
262 |
+
return NotImplemented
|
263 |
+
return self.%NAME%(other)
|
264 |
+
"""
|
265 |
+
|
266 |
+
return_mpf = "; obj = new(mpf); obj._mpf_ = val; return obj"
|
267 |
+
return_mpc = "; obj = new(mpc); obj._mpc_ = val; return obj"
|
268 |
+
|
269 |
+
mpf_pow_same = """
|
270 |
+
try:
|
271 |
+
val = mpf_pow(sval, tval, prec, rounding) %s
|
272 |
+
except ComplexResult:
|
273 |
+
if mpf.context.trap_complex:
|
274 |
+
raise
|
275 |
+
mpc = mpf.context.mpc
|
276 |
+
val = mpc_pow((sval, fzero), (tval, fzero), prec, rounding) %s
|
277 |
+
""" % (return_mpf, return_mpc)
|
278 |
+
|
279 |
+
def binary_op(name, with_mpf='', with_int='', with_mpc=''):
|
280 |
+
code = mpf_binary_op
|
281 |
+
code = code.replace("%WITH_INT%", with_int)
|
282 |
+
code = code.replace("%WITH_MPC%", with_mpc)
|
283 |
+
code = code.replace("%WITH_MPF%", with_mpf)
|
284 |
+
code = code.replace("%NAME%", name)
|
285 |
+
np = {}
|
286 |
+
exec_(code, globals(), np)
|
287 |
+
return np[name]
|
288 |
+
|
289 |
+
_mpf.__eq__ = binary_op('__eq__',
|
290 |
+
'return mpf_eq(sval, tval)',
|
291 |
+
'return mpf_eq(sval, from_int(other))',
|
292 |
+
'return (tval[1] == fzero) and mpf_eq(tval[0], sval)')
|
293 |
+
|
294 |
+
_mpf.__add__ = binary_op('__add__',
|
295 |
+
'val = mpf_add(sval, tval, prec, rounding)' + return_mpf,
|
296 |
+
'val = mpf_add(sval, from_int(other), prec, rounding)' + return_mpf,
|
297 |
+
'val = mpc_add_mpf(tval, sval, prec, rounding)' + return_mpc)
|
298 |
+
|
299 |
+
_mpf.__sub__ = binary_op('__sub__',
|
300 |
+
'val = mpf_sub(sval, tval, prec, rounding)' + return_mpf,
|
301 |
+
'val = mpf_sub(sval, from_int(other), prec, rounding)' + return_mpf,
|
302 |
+
'val = mpc_sub((sval, fzero), tval, prec, rounding)' + return_mpc)
|
303 |
+
|
304 |
+
_mpf.__mul__ = binary_op('__mul__',
|
305 |
+
'val = mpf_mul(sval, tval, prec, rounding)' + return_mpf,
|
306 |
+
'val = mpf_mul_int(sval, other, prec, rounding)' + return_mpf,
|
307 |
+
'val = mpc_mul_mpf(tval, sval, prec, rounding)' + return_mpc)
|
308 |
+
|
309 |
+
_mpf.__div__ = binary_op('__div__',
|
310 |
+
'val = mpf_div(sval, tval, prec, rounding)' + return_mpf,
|
311 |
+
'val = mpf_div(sval, from_int(other), prec, rounding)' + return_mpf,
|
312 |
+
'val = mpc_mpf_div(sval, tval, prec, rounding)' + return_mpc)
|
313 |
+
|
314 |
+
_mpf.__mod__ = binary_op('__mod__',
|
315 |
+
'val = mpf_mod(sval, tval, prec, rounding)' + return_mpf,
|
316 |
+
'val = mpf_mod(sval, from_int(other), prec, rounding)' + return_mpf,
|
317 |
+
'raise NotImplementedError("complex modulo")')
|
318 |
+
|
319 |
+
_mpf.__pow__ = binary_op('__pow__',
|
320 |
+
mpf_pow_same,
|
321 |
+
'val = mpf_pow_int(sval, other, prec, rounding)' + return_mpf,
|
322 |
+
'val = mpc_pow((sval, fzero), tval, prec, rounding)' + return_mpc)
|
323 |
+
|
324 |
+
_mpf.__radd__ = _mpf.__add__
|
325 |
+
_mpf.__rmul__ = _mpf.__mul__
|
326 |
+
_mpf.__truediv__ = _mpf.__div__
|
327 |
+
_mpf.__rtruediv__ = _mpf.__rdiv__
|
328 |
+
|
329 |
+
|
330 |
+
class _constant(_mpf):
|
331 |
+
"""Represents a mathematical constant with dynamic precision.
|
332 |
+
When printed or used in an arithmetic operation, a constant
|
333 |
+
is converted to a regular mpf at the working precision. A
|
334 |
+
regular mpf can also be obtained using the operation +x."""
|
335 |
+
|
336 |
+
def __new__(cls, func, name, docname=''):
|
337 |
+
a = object.__new__(cls)
|
338 |
+
a.name = name
|
339 |
+
a.func = func
|
340 |
+
a.__doc__ = getattr(function_docs, docname, '')
|
341 |
+
return a
|
342 |
+
|
343 |
+
def __call__(self, prec=None, dps=None, rounding=None):
|
344 |
+
prec2, rounding2 = self.context._prec_rounding
|
345 |
+
if not prec: prec = prec2
|
346 |
+
if not rounding: rounding = rounding2
|
347 |
+
if dps: prec = dps_to_prec(dps)
|
348 |
+
return self.context.make_mpf(self.func(prec, rounding))
|
349 |
+
|
350 |
+
@property
|
351 |
+
def _mpf_(self):
|
352 |
+
prec, rounding = self.context._prec_rounding
|
353 |
+
return self.func(prec, rounding)
|
354 |
+
|
355 |
+
def __repr__(self):
|
356 |
+
return "<%s: %s~>" % (self.name, self.context.nstr(self(dps=15)))
|
357 |
+
|
358 |
+
|
359 |
+
class _mpc(mpnumeric):
|
360 |
+
"""
|
361 |
+
An mpc represents a complex number using a pair of mpf:s (one
|
362 |
+
for the real part and another for the imaginary part.) The mpc
|
363 |
+
class behaves fairly similarly to Python's complex type.
|
364 |
+
"""
|
365 |
+
|
366 |
+
__slots__ = ['_mpc_']
|
367 |
+
|
368 |
+
def __new__(cls, real=0, imag=0):
|
369 |
+
s = object.__new__(cls)
|
370 |
+
if isinstance(real, complex_types):
|
371 |
+
real, imag = real.real, real.imag
|
372 |
+
elif hasattr(real, '_mpc_'):
|
373 |
+
s._mpc_ = real._mpc_
|
374 |
+
return s
|
375 |
+
real = cls.context.mpf(real)
|
376 |
+
imag = cls.context.mpf(imag)
|
377 |
+
s._mpc_ = (real._mpf_, imag._mpf_)
|
378 |
+
return s
|
379 |
+
|
380 |
+
real = property(lambda self: self.context.make_mpf(self._mpc_[0]))
|
381 |
+
imag = property(lambda self: self.context.make_mpf(self._mpc_[1]))
|
382 |
+
|
383 |
+
def __getstate__(self):
|
384 |
+
return to_pickable(self._mpc_[0]), to_pickable(self._mpc_[1])
|
385 |
+
|
386 |
+
def __setstate__(self, val):
|
387 |
+
self._mpc_ = from_pickable(val[0]), from_pickable(val[1])
|
388 |
+
|
389 |
+
def __repr__(s):
|
390 |
+
if s.context.pretty:
|
391 |
+
return str(s)
|
392 |
+
r = repr(s.real)[4:-1]
|
393 |
+
i = repr(s.imag)[4:-1]
|
394 |
+
return "%s(real=%s, imag=%s)" % (type(s).__name__, r, i)
|
395 |
+
|
396 |
+
def __str__(s):
|
397 |
+
return "(%s)" % mpc_to_str(s._mpc_, s.context._str_digits)
|
398 |
+
|
399 |
+
def __complex__(s):
|
400 |
+
return mpc_to_complex(s._mpc_, rnd=s.context._prec_rounding[1])
|
401 |
+
|
402 |
+
def __pos__(s):
|
403 |
+
cls, new, (prec, rounding) = s._ctxdata
|
404 |
+
v = new(cls)
|
405 |
+
v._mpc_ = mpc_pos(s._mpc_, prec, rounding)
|
406 |
+
return v
|
407 |
+
|
408 |
+
def __abs__(s):
|
409 |
+
prec, rounding = s.context._prec_rounding
|
410 |
+
v = new(s.context.mpf)
|
411 |
+
v._mpf_ = mpc_abs(s._mpc_, prec, rounding)
|
412 |
+
return v
|
413 |
+
|
414 |
+
def __neg__(s):
|
415 |
+
cls, new, (prec, rounding) = s._ctxdata
|
416 |
+
v = new(cls)
|
417 |
+
v._mpc_ = mpc_neg(s._mpc_, prec, rounding)
|
418 |
+
return v
|
419 |
+
|
420 |
+
def conjugate(s):
|
421 |
+
cls, new, (prec, rounding) = s._ctxdata
|
422 |
+
v = new(cls)
|
423 |
+
v._mpc_ = mpc_conjugate(s._mpc_, prec, rounding)
|
424 |
+
return v
|
425 |
+
|
426 |
+
def __nonzero__(s):
|
427 |
+
return mpc_is_nonzero(s._mpc_)
|
428 |
+
|
429 |
+
__bool__ = __nonzero__
|
430 |
+
|
431 |
+
def __hash__(s):
|
432 |
+
return mpc_hash(s._mpc_)
|
433 |
+
|
434 |
+
@classmethod
|
435 |
+
def mpc_convert_lhs(cls, x):
|
436 |
+
try:
|
437 |
+
y = cls.context.convert(x)
|
438 |
+
return y
|
439 |
+
except TypeError:
|
440 |
+
return NotImplemented
|
441 |
+
|
442 |
+
def __eq__(s, t):
|
443 |
+
if not hasattr(t, '_mpc_'):
|
444 |
+
if isinstance(t, str):
|
445 |
+
return False
|
446 |
+
t = s.mpc_convert_lhs(t)
|
447 |
+
if t is NotImplemented:
|
448 |
+
return t
|
449 |
+
return s.real == t.real and s.imag == t.imag
|
450 |
+
|
451 |
+
def __ne__(s, t):
|
452 |
+
b = s.__eq__(t)
|
453 |
+
if b is NotImplemented:
|
454 |
+
return b
|
455 |
+
return not b
|
456 |
+
|
457 |
+
def _compare(*args):
|
458 |
+
raise TypeError("no ordering relation is defined for complex numbers")
|
459 |
+
|
460 |
+
__gt__ = _compare
|
461 |
+
__le__ = _compare
|
462 |
+
__gt__ = _compare
|
463 |
+
__ge__ = _compare
|
464 |
+
|
465 |
+
def __add__(s, t):
|
466 |
+
cls, new, (prec, rounding) = s._ctxdata
|
467 |
+
if not hasattr(t, '_mpc_'):
|
468 |
+
t = s.mpc_convert_lhs(t)
|
469 |
+
if t is NotImplemented:
|
470 |
+
return t
|
471 |
+
if hasattr(t, '_mpf_'):
|
472 |
+
v = new(cls)
|
473 |
+
v._mpc_ = mpc_add_mpf(s._mpc_, t._mpf_, prec, rounding)
|
474 |
+
return v
|
475 |
+
v = new(cls)
|
476 |
+
v._mpc_ = mpc_add(s._mpc_, t._mpc_, prec, rounding)
|
477 |
+
return v
|
478 |
+
|
479 |
+
def __sub__(s, t):
|
480 |
+
cls, new, (prec, rounding) = s._ctxdata
|
481 |
+
if not hasattr(t, '_mpc_'):
|
482 |
+
t = s.mpc_convert_lhs(t)
|
483 |
+
if t is NotImplemented:
|
484 |
+
return t
|
485 |
+
if hasattr(t, '_mpf_'):
|
486 |
+
v = new(cls)
|
487 |
+
v._mpc_ = mpc_sub_mpf(s._mpc_, t._mpf_, prec, rounding)
|
488 |
+
return v
|
489 |
+
v = new(cls)
|
490 |
+
v._mpc_ = mpc_sub(s._mpc_, t._mpc_, prec, rounding)
|
491 |
+
return v
|
492 |
+
|
493 |
+
def __mul__(s, t):
|
494 |
+
cls, new, (prec, rounding) = s._ctxdata
|
495 |
+
if not hasattr(t, '_mpc_'):
|
496 |
+
if isinstance(t, int_types):
|
497 |
+
v = new(cls)
|
498 |
+
v._mpc_ = mpc_mul_int(s._mpc_, t, prec, rounding)
|
499 |
+
return v
|
500 |
+
t = s.mpc_convert_lhs(t)
|
501 |
+
if t is NotImplemented:
|
502 |
+
return t
|
503 |
+
if hasattr(t, '_mpf_'):
|
504 |
+
v = new(cls)
|
505 |
+
v._mpc_ = mpc_mul_mpf(s._mpc_, t._mpf_, prec, rounding)
|
506 |
+
return v
|
507 |
+
t = s.mpc_convert_lhs(t)
|
508 |
+
v = new(cls)
|
509 |
+
v._mpc_ = mpc_mul(s._mpc_, t._mpc_, prec, rounding)
|
510 |
+
return v
|
511 |
+
|
512 |
+
def __div__(s, t):
|
513 |
+
cls, new, (prec, rounding) = s._ctxdata
|
514 |
+
if not hasattr(t, '_mpc_'):
|
515 |
+
t = s.mpc_convert_lhs(t)
|
516 |
+
if t is NotImplemented:
|
517 |
+
return t
|
518 |
+
if hasattr(t, '_mpf_'):
|
519 |
+
v = new(cls)
|
520 |
+
v._mpc_ = mpc_div_mpf(s._mpc_, t._mpf_, prec, rounding)
|
521 |
+
return v
|
522 |
+
v = new(cls)
|
523 |
+
v._mpc_ = mpc_div(s._mpc_, t._mpc_, prec, rounding)
|
524 |
+
return v
|
525 |
+
|
526 |
+
def __pow__(s, t):
|
527 |
+
cls, new, (prec, rounding) = s._ctxdata
|
528 |
+
if isinstance(t, int_types):
|
529 |
+
v = new(cls)
|
530 |
+
v._mpc_ = mpc_pow_int(s._mpc_, t, prec, rounding)
|
531 |
+
return v
|
532 |
+
t = s.mpc_convert_lhs(t)
|
533 |
+
if t is NotImplemented:
|
534 |
+
return t
|
535 |
+
v = new(cls)
|
536 |
+
if hasattr(t, '_mpf_'):
|
537 |
+
v._mpc_ = mpc_pow_mpf(s._mpc_, t._mpf_, prec, rounding)
|
538 |
+
else:
|
539 |
+
v._mpc_ = mpc_pow(s._mpc_, t._mpc_, prec, rounding)
|
540 |
+
return v
|
541 |
+
|
542 |
+
__radd__ = __add__
|
543 |
+
|
544 |
+
def __rsub__(s, t):
|
545 |
+
t = s.mpc_convert_lhs(t)
|
546 |
+
if t is NotImplemented:
|
547 |
+
return t
|
548 |
+
return t - s
|
549 |
+
|
550 |
+
def __rmul__(s, t):
|
551 |
+
cls, new, (prec, rounding) = s._ctxdata
|
552 |
+
if isinstance(t, int_types):
|
553 |
+
v = new(cls)
|
554 |
+
v._mpc_ = mpc_mul_int(s._mpc_, t, prec, rounding)
|
555 |
+
return v
|
556 |
+
t = s.mpc_convert_lhs(t)
|
557 |
+
if t is NotImplemented:
|
558 |
+
return t
|
559 |
+
return t * s
|
560 |
+
|
561 |
+
def __rdiv__(s, t):
|
562 |
+
t = s.mpc_convert_lhs(t)
|
563 |
+
if t is NotImplemented:
|
564 |
+
return t
|
565 |
+
return t / s
|
566 |
+
|
567 |
+
def __rpow__(s, t):
|
568 |
+
t = s.mpc_convert_lhs(t)
|
569 |
+
if t is NotImplemented:
|
570 |
+
return t
|
571 |
+
return t ** s
|
572 |
+
|
573 |
+
__truediv__ = __div__
|
574 |
+
__rtruediv__ = __rdiv__
|
575 |
+
|
576 |
+
def ae(s, t, rel_eps=None, abs_eps=None):
|
577 |
+
return s.context.almosteq(s, t, rel_eps, abs_eps)
|
578 |
+
|
579 |
+
|
580 |
+
complex_types = (complex, _mpc)
|
581 |
+
|
582 |
+
|
583 |
+
class PythonMPContext(object):
|
584 |
+
|
585 |
+
def __init__(ctx):
|
586 |
+
ctx._prec_rounding = [53, round_nearest]
|
587 |
+
ctx.mpf = type('mpf', (_mpf,), {})
|
588 |
+
ctx.mpc = type('mpc', (_mpc,), {})
|
589 |
+
ctx.mpf._ctxdata = [ctx.mpf, new, ctx._prec_rounding]
|
590 |
+
ctx.mpc._ctxdata = [ctx.mpc, new, ctx._prec_rounding]
|
591 |
+
ctx.mpf.context = ctx
|
592 |
+
ctx.mpc.context = ctx
|
593 |
+
ctx.constant = type('constant', (_constant,), {})
|
594 |
+
ctx.constant._ctxdata = [ctx.mpf, new, ctx._prec_rounding]
|
595 |
+
ctx.constant.context = ctx
|
596 |
+
|
597 |
+
def make_mpf(ctx, v):
|
598 |
+
a = new(ctx.mpf)
|
599 |
+
a._mpf_ = v
|
600 |
+
return a
|
601 |
+
|
602 |
+
def make_mpc(ctx, v):
|
603 |
+
a = new(ctx.mpc)
|
604 |
+
a._mpc_ = v
|
605 |
+
return a
|
606 |
+
|
607 |
+
def default(ctx):
|
608 |
+
ctx._prec = ctx._prec_rounding[0] = 53
|
609 |
+
ctx._dps = 15
|
610 |
+
ctx.trap_complex = False
|
611 |
+
|
612 |
+
def _set_prec(ctx, n):
|
613 |
+
ctx._prec = ctx._prec_rounding[0] = max(1, int(n))
|
614 |
+
ctx._dps = prec_to_dps(n)
|
615 |
+
|
616 |
+
def _set_dps(ctx, n):
|
617 |
+
ctx._prec = ctx._prec_rounding[0] = dps_to_prec(n)
|
618 |
+
ctx._dps = max(1, int(n))
|
619 |
+
|
620 |
+
prec = property(lambda ctx: ctx._prec, _set_prec)
|
621 |
+
dps = property(lambda ctx: ctx._dps, _set_dps)
|
622 |
+
|
623 |
+
def convert(ctx, x, strings=True):
|
624 |
+
"""
|
625 |
+
Converts *x* to an ``mpf`` or ``mpc``. If *x* is of type ``mpf``,
|
626 |
+
``mpc``, ``int``, ``float``, ``complex``, the conversion
|
627 |
+
will be performed losslessly.
|
628 |
+
|
629 |
+
If *x* is a string, the result will be rounded to the present
|
630 |
+
working precision. Strings representing fractions or complex
|
631 |
+
numbers are permitted.
|
632 |
+
|
633 |
+
>>> from mpmath import *
|
634 |
+
>>> mp.dps = 15; mp.pretty = False
|
635 |
+
>>> mpmathify(3.5)
|
636 |
+
mpf('3.5')
|
637 |
+
>>> mpmathify('2.1')
|
638 |
+
mpf('2.1000000000000001')
|
639 |
+
>>> mpmathify('3/4')
|
640 |
+
mpf('0.75')
|
641 |
+
>>> mpmathify('2+3j')
|
642 |
+
mpc(real='2.0', imag='3.0')
|
643 |
+
|
644 |
+
"""
|
645 |
+
if type(x) in ctx.types: return x
|
646 |
+
if isinstance(x, int_types): return ctx.make_mpf(from_int(x))
|
647 |
+
if isinstance(x, float): return ctx.make_mpf(from_float(x))
|
648 |
+
if isinstance(x, complex):
|
649 |
+
return ctx.make_mpc((from_float(x.real), from_float(x.imag)))
|
650 |
+
if type(x).__module__ == 'numpy': return ctx.npconvert(x)
|
651 |
+
if isinstance(x, numbers.Rational): # e.g. Fraction
|
652 |
+
try: x = rational.mpq(int(x.numerator), int(x.denominator))
|
653 |
+
except: pass
|
654 |
+
prec, rounding = ctx._prec_rounding
|
655 |
+
if isinstance(x, rational.mpq):
|
656 |
+
p, q = x._mpq_
|
657 |
+
return ctx.make_mpf(from_rational(p, q, prec))
|
658 |
+
if strings and isinstance(x, basestring):
|
659 |
+
try:
|
660 |
+
_mpf_ = from_str(x, prec, rounding)
|
661 |
+
return ctx.make_mpf(_mpf_)
|
662 |
+
except ValueError:
|
663 |
+
pass
|
664 |
+
if hasattr(x, '_mpf_'): return ctx.make_mpf(x._mpf_)
|
665 |
+
if hasattr(x, '_mpc_'): return ctx.make_mpc(x._mpc_)
|
666 |
+
if hasattr(x, '_mpmath_'):
|
667 |
+
return ctx.convert(x._mpmath_(prec, rounding))
|
668 |
+
if type(x).__module__ == 'decimal':
|
669 |
+
try: return ctx.make_mpf(from_Decimal(x, prec, rounding))
|
670 |
+
except: pass
|
671 |
+
return ctx._convert_fallback(x, strings)
|
672 |
+
|
673 |
+
def npconvert(ctx, x):
|
674 |
+
"""
|
675 |
+
Converts *x* to an ``mpf`` or ``mpc``. *x* should be a numpy
|
676 |
+
scalar.
|
677 |
+
"""
|
678 |
+
import numpy as np
|
679 |
+
if isinstance(x, np.integer): return ctx.make_mpf(from_int(int(x)))
|
680 |
+
if isinstance(x, np.floating): return ctx.make_mpf(from_npfloat(x))
|
681 |
+
if isinstance(x, np.complexfloating):
|
682 |
+
return ctx.make_mpc((from_npfloat(x.real), from_npfloat(x.imag)))
|
683 |
+
raise TypeError("cannot create mpf from " + repr(x))
|
684 |
+
|
685 |
+
def isnan(ctx, x):
|
686 |
+
"""
|
687 |
+
Return *True* if *x* is a NaN (not-a-number), or for a complex
|
688 |
+
number, whether either the real or complex part is NaN;
|
689 |
+
otherwise return *False*::
|
690 |
+
|
691 |
+
>>> from mpmath import *
|
692 |
+
>>> isnan(3.14)
|
693 |
+
False
|
694 |
+
>>> isnan(nan)
|
695 |
+
True
|
696 |
+
>>> isnan(mpc(3.14,2.72))
|
697 |
+
False
|
698 |
+
>>> isnan(mpc(3.14,nan))
|
699 |
+
True
|
700 |
+
|
701 |
+
"""
|
702 |
+
if hasattr(x, "_mpf_"):
|
703 |
+
return x._mpf_ == fnan
|
704 |
+
if hasattr(x, "_mpc_"):
|
705 |
+
return fnan in x._mpc_
|
706 |
+
if isinstance(x, int_types) or isinstance(x, rational.mpq):
|
707 |
+
return False
|
708 |
+
x = ctx.convert(x)
|
709 |
+
if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):
|
710 |
+
return ctx.isnan(x)
|
711 |
+
raise TypeError("isnan() needs a number as input")
|
712 |
+
|
713 |
+
def isinf(ctx, x):
|
714 |
+
"""
|
715 |
+
Return *True* if the absolute value of *x* is infinite;
|
716 |
+
otherwise return *False*::
|
717 |
+
|
718 |
+
>>> from mpmath import *
|
719 |
+
>>> isinf(inf)
|
720 |
+
True
|
721 |
+
>>> isinf(-inf)
|
722 |
+
True
|
723 |
+
>>> isinf(3)
|
724 |
+
False
|
725 |
+
>>> isinf(3+4j)
|
726 |
+
False
|
727 |
+
>>> isinf(mpc(3,inf))
|
728 |
+
True
|
729 |
+
>>> isinf(mpc(inf,3))
|
730 |
+
True
|
731 |
+
|
732 |
+
"""
|
733 |
+
if hasattr(x, "_mpf_"):
|
734 |
+
return x._mpf_ in (finf, fninf)
|
735 |
+
if hasattr(x, "_mpc_"):
|
736 |
+
re, im = x._mpc_
|
737 |
+
return re in (finf, fninf) or im in (finf, fninf)
|
738 |
+
if isinstance(x, int_types) or isinstance(x, rational.mpq):
|
739 |
+
return False
|
740 |
+
x = ctx.convert(x)
|
741 |
+
if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):
|
742 |
+
return ctx.isinf(x)
|
743 |
+
raise TypeError("isinf() needs a number as input")
|
744 |
+
|
745 |
+
def isnormal(ctx, x):
|
746 |
+
"""
|
747 |
+
Determine whether *x* is "normal" in the sense of floating-point
|
748 |
+
representation; that is, return *False* if *x* is zero, an
|
749 |
+
infinity or NaN; otherwise return *True*. By extension, a
|
750 |
+
complex number *x* is considered "normal" if its magnitude is
|
751 |
+
normal::
|
752 |
+
|
753 |
+
>>> from mpmath import *
|
754 |
+
>>> isnormal(3)
|
755 |
+
True
|
756 |
+
>>> isnormal(0)
|
757 |
+
False
|
758 |
+
>>> isnormal(inf); isnormal(-inf); isnormal(nan)
|
759 |
+
False
|
760 |
+
False
|
761 |
+
False
|
762 |
+
>>> isnormal(0+0j)
|
763 |
+
False
|
764 |
+
>>> isnormal(0+3j)
|
765 |
+
True
|
766 |
+
>>> isnormal(mpc(2,nan))
|
767 |
+
False
|
768 |
+
"""
|
769 |
+
if hasattr(x, "_mpf_"):
|
770 |
+
return bool(x._mpf_[1])
|
771 |
+
if hasattr(x, "_mpc_"):
|
772 |
+
re, im = x._mpc_
|
773 |
+
re_normal = bool(re[1])
|
774 |
+
im_normal = bool(im[1])
|
775 |
+
if re == fzero: return im_normal
|
776 |
+
if im == fzero: return re_normal
|
777 |
+
return re_normal and im_normal
|
778 |
+
if isinstance(x, int_types) or isinstance(x, rational.mpq):
|
779 |
+
return bool(x)
|
780 |
+
x = ctx.convert(x)
|
781 |
+
if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):
|
782 |
+
return ctx.isnormal(x)
|
783 |
+
raise TypeError("isnormal() needs a number as input")
|
784 |
+
|
785 |
+
def isint(ctx, x, gaussian=False):
|
786 |
+
"""
|
787 |
+
Return *True* if *x* is integer-valued; otherwise return
|
788 |
+
*False*::
|
789 |
+
|
790 |
+
>>> from mpmath import *
|
791 |
+
>>> isint(3)
|
792 |
+
True
|
793 |
+
>>> isint(mpf(3))
|
794 |
+
True
|
795 |
+
>>> isint(3.2)
|
796 |
+
False
|
797 |
+
>>> isint(inf)
|
798 |
+
False
|
799 |
+
|
800 |
+
Optionally, Gaussian integers can be checked for::
|
801 |
+
|
802 |
+
>>> isint(3+0j)
|
803 |
+
True
|
804 |
+
>>> isint(3+2j)
|
805 |
+
False
|
806 |
+
>>> isint(3+2j, gaussian=True)
|
807 |
+
True
|
808 |
+
|
809 |
+
"""
|
810 |
+
if isinstance(x, int_types):
|
811 |
+
return True
|
812 |
+
if hasattr(x, "_mpf_"):
|
813 |
+
sign, man, exp, bc = xval = x._mpf_
|
814 |
+
return bool((man and exp >= 0) or xval == fzero)
|
815 |
+
if hasattr(x, "_mpc_"):
|
816 |
+
re, im = x._mpc_
|
817 |
+
rsign, rman, rexp, rbc = re
|
818 |
+
isign, iman, iexp, ibc = im
|
819 |
+
re_isint = (rman and rexp >= 0) or re == fzero
|
820 |
+
if gaussian:
|
821 |
+
im_isint = (iman and iexp >= 0) or im == fzero
|
822 |
+
return re_isint and im_isint
|
823 |
+
return re_isint and im == fzero
|
824 |
+
if isinstance(x, rational.mpq):
|
825 |
+
p, q = x._mpq_
|
826 |
+
return p % q == 0
|
827 |
+
x = ctx.convert(x)
|
828 |
+
if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):
|
829 |
+
return ctx.isint(x, gaussian)
|
830 |
+
raise TypeError("isint() needs a number as input")
|
831 |
+
|
832 |
+
def fsum(ctx, terms, absolute=False, squared=False):
|
833 |
+
"""
|
834 |
+
Calculates a sum containing a finite number of terms (for infinite
|
835 |
+
series, see :func:`~mpmath.nsum`). The terms will be converted to
|
836 |
+
mpmath numbers. For len(terms) > 2, this function is generally
|
837 |
+
faster and produces more accurate results than the builtin
|
838 |
+
Python function :func:`sum`.
|
839 |
+
|
840 |
+
>>> from mpmath import *
|
841 |
+
>>> mp.dps = 15; mp.pretty = False
|
842 |
+
>>> fsum([1, 2, 0.5, 7])
|
843 |
+
mpf('10.5')
|
844 |
+
|
845 |
+
With squared=True each term is squared, and with absolute=True
|
846 |
+
the absolute value of each term is used.
|
847 |
+
"""
|
848 |
+
prec, rnd = ctx._prec_rounding
|
849 |
+
real = []
|
850 |
+
imag = []
|
851 |
+
for term in terms:
|
852 |
+
reval = imval = 0
|
853 |
+
if hasattr(term, "_mpf_"):
|
854 |
+
reval = term._mpf_
|
855 |
+
elif hasattr(term, "_mpc_"):
|
856 |
+
reval, imval = term._mpc_
|
857 |
+
else:
|
858 |
+
term = ctx.convert(term)
|
859 |
+
if hasattr(term, "_mpf_"):
|
860 |
+
reval = term._mpf_
|
861 |
+
elif hasattr(term, "_mpc_"):
|
862 |
+
reval, imval = term._mpc_
|
863 |
+
else:
|
864 |
+
raise NotImplementedError
|
865 |
+
if imval:
|
866 |
+
if squared:
|
867 |
+
if absolute:
|
868 |
+
real.append(mpf_mul(reval,reval))
|
869 |
+
real.append(mpf_mul(imval,imval))
|
870 |
+
else:
|
871 |
+
reval, imval = mpc_pow_int((reval,imval),2,prec+10)
|
872 |
+
real.append(reval)
|
873 |
+
imag.append(imval)
|
874 |
+
elif absolute:
|
875 |
+
real.append(mpc_abs((reval,imval), prec))
|
876 |
+
else:
|
877 |
+
real.append(reval)
|
878 |
+
imag.append(imval)
|
879 |
+
else:
|
880 |
+
if squared:
|
881 |
+
reval = mpf_mul(reval, reval)
|
882 |
+
elif absolute:
|
883 |
+
reval = mpf_abs(reval)
|
884 |
+
real.append(reval)
|
885 |
+
s = mpf_sum(real, prec, rnd, absolute)
|
886 |
+
if imag:
|
887 |
+
s = ctx.make_mpc((s, mpf_sum(imag, prec, rnd)))
|
888 |
+
else:
|
889 |
+
s = ctx.make_mpf(s)
|
890 |
+
return s
|
891 |
+
|
892 |
+
def fdot(ctx, A, B=None, conjugate=False):
|
893 |
+
r"""
|
894 |
+
Computes the dot product of the iterables `A` and `B`,
|
895 |
+
|
896 |
+
.. math ::
|
897 |
+
|
898 |
+
\sum_{k=0} A_k B_k.
|
899 |
+
|
900 |
+
Alternatively, :func:`~mpmath.fdot` accepts a single iterable of pairs.
|
901 |
+
In other words, ``fdot(A,B)`` and ``fdot(zip(A,B))`` are equivalent.
|
902 |
+
The elements are automatically converted to mpmath numbers.
|
903 |
+
|
904 |
+
With ``conjugate=True``, the elements in the second vector
|
905 |
+
will be conjugated:
|
906 |
+
|
907 |
+
.. math ::
|
908 |
+
|
909 |
+
\sum_{k=0} A_k \overline{B_k}
|
910 |
+
|
911 |
+
**Examples**
|
912 |
+
|
913 |
+
>>> from mpmath import *
|
914 |
+
>>> mp.dps = 15; mp.pretty = False
|
915 |
+
>>> A = [2, 1.5, 3]
|
916 |
+
>>> B = [1, -1, 2]
|
917 |
+
>>> fdot(A, B)
|
918 |
+
mpf('6.5')
|
919 |
+
>>> list(zip(A, B))
|
920 |
+
[(2, 1), (1.5, -1), (3, 2)]
|
921 |
+
>>> fdot(_)
|
922 |
+
mpf('6.5')
|
923 |
+
>>> A = [2, 1.5, 3j]
|
924 |
+
>>> B = [1+j, 3, -1-j]
|
925 |
+
>>> fdot(A, B)
|
926 |
+
mpc(real='9.5', imag='-1.0')
|
927 |
+
>>> fdot(A, B, conjugate=True)
|
928 |
+
mpc(real='3.5', imag='-5.0')
|
929 |
+
|
930 |
+
"""
|
931 |
+
if B is not None:
|
932 |
+
A = zip(A, B)
|
933 |
+
prec, rnd = ctx._prec_rounding
|
934 |
+
real = []
|
935 |
+
imag = []
|
936 |
+
hasattr_ = hasattr
|
937 |
+
types = (ctx.mpf, ctx.mpc)
|
938 |
+
for a, b in A:
|
939 |
+
if type(a) not in types: a = ctx.convert(a)
|
940 |
+
if type(b) not in types: b = ctx.convert(b)
|
941 |
+
a_real = hasattr_(a, "_mpf_")
|
942 |
+
b_real = hasattr_(b, "_mpf_")
|
943 |
+
if a_real and b_real:
|
944 |
+
real.append(mpf_mul(a._mpf_, b._mpf_))
|
945 |
+
continue
|
946 |
+
a_complex = hasattr_(a, "_mpc_")
|
947 |
+
b_complex = hasattr_(b, "_mpc_")
|
948 |
+
if a_real and b_complex:
|
949 |
+
aval = a._mpf_
|
950 |
+
bre, bim = b._mpc_
|
951 |
+
if conjugate:
|
952 |
+
bim = mpf_neg(bim)
|
953 |
+
real.append(mpf_mul(aval, bre))
|
954 |
+
imag.append(mpf_mul(aval, bim))
|
955 |
+
elif b_real and a_complex:
|
956 |
+
are, aim = a._mpc_
|
957 |
+
bval = b._mpf_
|
958 |
+
real.append(mpf_mul(are, bval))
|
959 |
+
imag.append(mpf_mul(aim, bval))
|
960 |
+
elif a_complex and b_complex:
|
961 |
+
#re, im = mpc_mul(a._mpc_, b._mpc_, prec+20)
|
962 |
+
are, aim = a._mpc_
|
963 |
+
bre, bim = b._mpc_
|
964 |
+
if conjugate:
|
965 |
+
bim = mpf_neg(bim)
|
966 |
+
real.append(mpf_mul(are, bre))
|
967 |
+
real.append(mpf_neg(mpf_mul(aim, bim)))
|
968 |
+
imag.append(mpf_mul(are, bim))
|
969 |
+
imag.append(mpf_mul(aim, bre))
|
970 |
+
else:
|
971 |
+
raise NotImplementedError
|
972 |
+
s = mpf_sum(real, prec, rnd)
|
973 |
+
if imag:
|
974 |
+
s = ctx.make_mpc((s, mpf_sum(imag, prec, rnd)))
|
975 |
+
else:
|
976 |
+
s = ctx.make_mpf(s)
|
977 |
+
return s
|
978 |
+
|
979 |
+
def _wrap_libmp_function(ctx, mpf_f, mpc_f=None, mpi_f=None, doc="<no doc>"):
|
980 |
+
"""
|
981 |
+
Given a low-level mpf_ function, and optionally similar functions
|
982 |
+
for mpc_ and mpi_, defines the function as a context method.
|
983 |
+
|
984 |
+
It is assumed that the return type is the same as that of
|
985 |
+
the input; the exception is that propagation from mpf to mpc is possible
|
986 |
+
by raising ComplexResult.
|
987 |
+
|
988 |
+
"""
|
989 |
+
def f(x, **kwargs):
|
990 |
+
if type(x) not in ctx.types:
|
991 |
+
x = ctx.convert(x)
|
992 |
+
prec, rounding = ctx._prec_rounding
|
993 |
+
if kwargs:
|
994 |
+
prec = kwargs.get('prec', prec)
|
995 |
+
if 'dps' in kwargs:
|
996 |
+
prec = dps_to_prec(kwargs['dps'])
|
997 |
+
rounding = kwargs.get('rounding', rounding)
|
998 |
+
if hasattr(x, '_mpf_'):
|
999 |
+
try:
|
1000 |
+
return ctx.make_mpf(mpf_f(x._mpf_, prec, rounding))
|
1001 |
+
except ComplexResult:
|
1002 |
+
# Handle propagation to complex
|
1003 |
+
if ctx.trap_complex:
|
1004 |
+
raise
|
1005 |
+
return ctx.make_mpc(mpc_f((x._mpf_, fzero), prec, rounding))
|
1006 |
+
elif hasattr(x, '_mpc_'):
|
1007 |
+
return ctx.make_mpc(mpc_f(x._mpc_, prec, rounding))
|
1008 |
+
raise NotImplementedError("%s of a %s" % (name, type(x)))
|
1009 |
+
name = mpf_f.__name__[4:]
|
1010 |
+
f.__doc__ = function_docs.__dict__.get(name, "Computes the %s of x" % doc)
|
1011 |
+
return f
|
1012 |
+
|
1013 |
+
# Called by SpecialFunctions.__init__()
|
1014 |
+
@classmethod
|
1015 |
+
def _wrap_specfun(cls, name, f, wrap):
|
1016 |
+
if wrap:
|
1017 |
+
def f_wrapped(ctx, *args, **kwargs):
|
1018 |
+
convert = ctx.convert
|
1019 |
+
args = [convert(a) for a in args]
|
1020 |
+
prec = ctx.prec
|
1021 |
+
try:
|
1022 |
+
ctx.prec += 10
|
1023 |
+
retval = f(ctx, *args, **kwargs)
|
1024 |
+
finally:
|
1025 |
+
ctx.prec = prec
|
1026 |
+
return +retval
|
1027 |
+
else:
|
1028 |
+
f_wrapped = f
|
1029 |
+
f_wrapped.__doc__ = function_docs.__dict__.get(name, f.__doc__)
|
1030 |
+
setattr(cls, name, f_wrapped)
|
1031 |
+
|
1032 |
+
def _convert_param(ctx, x):
|
1033 |
+
if hasattr(x, "_mpc_"):
|
1034 |
+
v, im = x._mpc_
|
1035 |
+
if im != fzero:
|
1036 |
+
return x, 'C'
|
1037 |
+
elif hasattr(x, "_mpf_"):
|
1038 |
+
v = x._mpf_
|
1039 |
+
else:
|
1040 |
+
if type(x) in int_types:
|
1041 |
+
return int(x), 'Z'
|
1042 |
+
p = None
|
1043 |
+
if isinstance(x, tuple):
|
1044 |
+
p, q = x
|
1045 |
+
elif hasattr(x, '_mpq_'):
|
1046 |
+
p, q = x._mpq_
|
1047 |
+
elif isinstance(x, basestring) and '/' in x:
|
1048 |
+
p, q = x.split('/')
|
1049 |
+
p = int(p)
|
1050 |
+
q = int(q)
|
1051 |
+
if p is not None:
|
1052 |
+
if not p % q:
|
1053 |
+
return p // q, 'Z'
|
1054 |
+
return ctx.mpq(p,q), 'Q'
|
1055 |
+
x = ctx.convert(x)
|
1056 |
+
if hasattr(x, "_mpc_"):
|
1057 |
+
v, im = x._mpc_
|
1058 |
+
if im != fzero:
|
1059 |
+
return x, 'C'
|
1060 |
+
elif hasattr(x, "_mpf_"):
|
1061 |
+
v = x._mpf_
|
1062 |
+
else:
|
1063 |
+
return x, 'U'
|
1064 |
+
sign, man, exp, bc = v
|
1065 |
+
if man:
|
1066 |
+
if exp >= -4:
|
1067 |
+
if sign:
|
1068 |
+
man = -man
|
1069 |
+
if exp >= 0:
|
1070 |
+
return int(man) << exp, 'Z'
|
1071 |
+
if exp >= -4:
|
1072 |
+
p, q = int(man), (1<<(-exp))
|
1073 |
+
return ctx.mpq(p,q), 'Q'
|
1074 |
+
x = ctx.make_mpf(v)
|
1075 |
+
return x, 'R'
|
1076 |
+
elif not exp:
|
1077 |
+
return 0, 'Z'
|
1078 |
+
else:
|
1079 |
+
return x, 'U'
|
1080 |
+
|
1081 |
+
def _mpf_mag(ctx, x):
|
1082 |
+
sign, man, exp, bc = x
|
1083 |
+
if man:
|
1084 |
+
return exp+bc
|
1085 |
+
if x == fzero:
|
1086 |
+
return ctx.ninf
|
1087 |
+
if x == finf or x == fninf:
|
1088 |
+
return ctx.inf
|
1089 |
+
return ctx.nan
|
1090 |
+
|
1091 |
+
def mag(ctx, x):
|
1092 |
+
"""
|
1093 |
+
Quick logarithmic magnitude estimate of a number. Returns an
|
1094 |
+
integer or infinity `m` such that `|x| <= 2^m`. It is not
|
1095 |
+
guaranteed that `m` is an optimal bound, but it will never
|
1096 |
+
be too large by more than 2 (and probably not more than 1).
|
1097 |
+
|
1098 |
+
**Examples**
|
1099 |
+
|
1100 |
+
>>> from mpmath import *
|
1101 |
+
>>> mp.pretty = True
|
1102 |
+
>>> mag(10), mag(10.0), mag(mpf(10)), int(ceil(log(10,2)))
|
1103 |
+
(4, 4, 4, 4)
|
1104 |
+
>>> mag(10j), mag(10+10j)
|
1105 |
+
(4, 5)
|
1106 |
+
>>> mag(0.01), int(ceil(log(0.01,2)))
|
1107 |
+
(-6, -6)
|
1108 |
+
>>> mag(0), mag(inf), mag(-inf), mag(nan)
|
1109 |
+
(-inf, +inf, +inf, nan)
|
1110 |
+
|
1111 |
+
"""
|
1112 |
+
if hasattr(x, "_mpf_"):
|
1113 |
+
return ctx._mpf_mag(x._mpf_)
|
1114 |
+
elif hasattr(x, "_mpc_"):
|
1115 |
+
r, i = x._mpc_
|
1116 |
+
if r == fzero:
|
1117 |
+
return ctx._mpf_mag(i)
|
1118 |
+
if i == fzero:
|
1119 |
+
return ctx._mpf_mag(r)
|
1120 |
+
return 1+max(ctx._mpf_mag(r), ctx._mpf_mag(i))
|
1121 |
+
elif isinstance(x, int_types):
|
1122 |
+
if x:
|
1123 |
+
return bitcount(abs(x))
|
1124 |
+
return ctx.ninf
|
1125 |
+
elif isinstance(x, rational.mpq):
|
1126 |
+
p, q = x._mpq_
|
1127 |
+
if p:
|
1128 |
+
return 1 + bitcount(abs(p)) - bitcount(q)
|
1129 |
+
return ctx.ninf
|
1130 |
+
else:
|
1131 |
+
x = ctx.convert(x)
|
1132 |
+
if hasattr(x, "_mpf_") or hasattr(x, "_mpc_"):
|
1133 |
+
return ctx.mag(x)
|
1134 |
+
else:
|
1135 |
+
raise TypeError("requires an mpf/mpc")
|
1136 |
+
|
1137 |
+
|
1138 |
+
# Register with "numbers" ABC
|
1139 |
+
# We do not subclass, hence we do not use the @abstractmethod checks. While
|
1140 |
+
# this is less invasive it may turn out that we do not actually support
|
1141 |
+
# parts of the expected interfaces. See
|
1142 |
+
# http://docs.python.org/2/library/numbers.html for list of abstract
|
1143 |
+
# methods.
|
1144 |
+
try:
|
1145 |
+
import numbers
|
1146 |
+
numbers.Complex.register(_mpc)
|
1147 |
+
numbers.Real.register(_mpf)
|
1148 |
+
except ImportError:
|
1149 |
+
pass
|
venv/lib/python3.10/site-packages/mpmath/function_docs.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/mpmath/identification.py
ADDED
@@ -0,0 +1,844 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Implements the PSLQ algorithm for integer relation detection,
|
3 |
+
and derivative algorithms for constant recognition.
|
4 |
+
"""
|
5 |
+
|
6 |
+
from .libmp.backend import xrange
|
7 |
+
from .libmp import int_types, sqrt_fixed
|
8 |
+
|
9 |
+
# round to nearest integer (can be done more elegantly...)
|
10 |
+
def round_fixed(x, prec):
|
11 |
+
return ((x + (1<<(prec-1))) >> prec) << prec
|
12 |
+
|
13 |
+
class IdentificationMethods(object):
|
14 |
+
pass
|
15 |
+
|
16 |
+
|
17 |
+
def pslq(ctx, x, tol=None, maxcoeff=1000, maxsteps=100, verbose=False):
|
18 |
+
r"""
|
19 |
+
Given a vector of real numbers `x = [x_0, x_1, ..., x_n]`, ``pslq(x)``
|
20 |
+
uses the PSLQ algorithm to find a list of integers
|
21 |
+
`[c_0, c_1, ..., c_n]` such that
|
22 |
+
|
23 |
+
.. math ::
|
24 |
+
|
25 |
+
|c_1 x_1 + c_2 x_2 + ... + c_n x_n| < \mathrm{tol}
|
26 |
+
|
27 |
+
and such that `\max |c_k| < \mathrm{maxcoeff}`. If no such vector
|
28 |
+
exists, :func:`~mpmath.pslq` returns ``None``. The tolerance defaults to
|
29 |
+
3/4 of the working precision.
|
30 |
+
|
31 |
+
**Examples**
|
32 |
+
|
33 |
+
Find rational approximations for `\pi`::
|
34 |
+
|
35 |
+
>>> from mpmath import *
|
36 |
+
>>> mp.dps = 15; mp.pretty = True
|
37 |
+
>>> pslq([-1, pi], tol=0.01)
|
38 |
+
[22, 7]
|
39 |
+
>>> pslq([-1, pi], tol=0.001)
|
40 |
+
[355, 113]
|
41 |
+
>>> mpf(22)/7; mpf(355)/113; +pi
|
42 |
+
3.14285714285714
|
43 |
+
3.14159292035398
|
44 |
+
3.14159265358979
|
45 |
+
|
46 |
+
Pi is not a rational number with denominator less than 1000::
|
47 |
+
|
48 |
+
>>> pslq([-1, pi])
|
49 |
+
>>>
|
50 |
+
|
51 |
+
To within the standard precision, it can however be approximated
|
52 |
+
by at least one rational number with denominator less than `10^{12}`::
|
53 |
+
|
54 |
+
>>> p, q = pslq([-1, pi], maxcoeff=10**12)
|
55 |
+
>>> print(p); print(q)
|
56 |
+
238410049439
|
57 |
+
75888275702
|
58 |
+
>>> mpf(p)/q
|
59 |
+
3.14159265358979
|
60 |
+
|
61 |
+
The PSLQ algorithm can be applied to long vectors. For example,
|
62 |
+
we can investigate the rational (in)dependence of integer square
|
63 |
+
roots::
|
64 |
+
|
65 |
+
>>> mp.dps = 30
|
66 |
+
>>> pslq([sqrt(n) for n in range(2, 5+1)])
|
67 |
+
>>>
|
68 |
+
>>> pslq([sqrt(n) for n in range(2, 6+1)])
|
69 |
+
>>>
|
70 |
+
>>> pslq([sqrt(n) for n in range(2, 8+1)])
|
71 |
+
[2, 0, 0, 0, 0, 0, -1]
|
72 |
+
|
73 |
+
**Machin formulas**
|
74 |
+
|
75 |
+
A famous formula for `\pi` is Machin's,
|
76 |
+
|
77 |
+
.. math ::
|
78 |
+
|
79 |
+
\frac{\pi}{4} = 4 \operatorname{acot} 5 - \operatorname{acot} 239
|
80 |
+
|
81 |
+
There are actually infinitely many formulas of this type. Two
|
82 |
+
others are
|
83 |
+
|
84 |
+
.. math ::
|
85 |
+
|
86 |
+
\frac{\pi}{4} = \operatorname{acot} 1
|
87 |
+
|
88 |
+
\frac{\pi}{4} = 12 \operatorname{acot} 49 + 32 \operatorname{acot} 57
|
89 |
+
+ 5 \operatorname{acot} 239 + 12 \operatorname{acot} 110443
|
90 |
+
|
91 |
+
We can easily verify the formulas using the PSLQ algorithm::
|
92 |
+
|
93 |
+
>>> mp.dps = 30
|
94 |
+
>>> pslq([pi/4, acot(1)])
|
95 |
+
[1, -1]
|
96 |
+
>>> pslq([pi/4, acot(5), acot(239)])
|
97 |
+
[1, -4, 1]
|
98 |
+
>>> pslq([pi/4, acot(49), acot(57), acot(239), acot(110443)])
|
99 |
+
[1, -12, -32, 5, -12]
|
100 |
+
|
101 |
+
We could try to generate a custom Machin-like formula by running
|
102 |
+
the PSLQ algorithm with a few inverse cotangent values, for example
|
103 |
+
acot(2), acot(3) ... acot(10). Unfortunately, there is a linear
|
104 |
+
dependence among these values, resulting in only that dependence
|
105 |
+
being detected, with a zero coefficient for `\pi`::
|
106 |
+
|
107 |
+
>>> pslq([pi] + [acot(n) for n in range(2,11)])
|
108 |
+
[0, 1, -1, 0, 0, 0, -1, 0, 0, 0]
|
109 |
+
|
110 |
+
We get better luck by removing linearly dependent terms::
|
111 |
+
|
112 |
+
>>> pslq([pi] + [acot(n) for n in range(2,11) if n not in (3, 5)])
|
113 |
+
[1, -8, 0, 0, 4, 0, 0, 0]
|
114 |
+
|
115 |
+
In other words, we found the following formula::
|
116 |
+
|
117 |
+
>>> 8*acot(2) - 4*acot(7)
|
118 |
+
3.14159265358979323846264338328
|
119 |
+
>>> +pi
|
120 |
+
3.14159265358979323846264338328
|
121 |
+
|
122 |
+
**Algorithm**
|
123 |
+
|
124 |
+
This is a fairly direct translation to Python of the pseudocode given by
|
125 |
+
David Bailey, "The PSLQ Integer Relation Algorithm":
|
126 |
+
http://www.cecm.sfu.ca/organics/papers/bailey/paper/html/node3.html
|
127 |
+
|
128 |
+
The present implementation uses fixed-point instead of floating-point
|
129 |
+
arithmetic, since this is significantly (about 7x) faster.
|
130 |
+
"""
|
131 |
+
|
132 |
+
n = len(x)
|
133 |
+
if n < 2:
|
134 |
+
raise ValueError("n cannot be less than 2")
|
135 |
+
|
136 |
+
# At too low precision, the algorithm becomes meaningless
|
137 |
+
prec = ctx.prec
|
138 |
+
if prec < 53:
|
139 |
+
raise ValueError("prec cannot be less than 53")
|
140 |
+
|
141 |
+
if verbose and prec // max(2,n) < 5:
|
142 |
+
print("Warning: precision for PSLQ may be too low")
|
143 |
+
|
144 |
+
target = int(prec * 0.75)
|
145 |
+
|
146 |
+
if tol is None:
|
147 |
+
tol = ctx.mpf(2)**(-target)
|
148 |
+
else:
|
149 |
+
tol = ctx.convert(tol)
|
150 |
+
|
151 |
+
extra = 60
|
152 |
+
prec += extra
|
153 |
+
|
154 |
+
if verbose:
|
155 |
+
print("PSLQ using prec %i and tol %s" % (prec, ctx.nstr(tol)))
|
156 |
+
|
157 |
+
tol = ctx.to_fixed(tol, prec)
|
158 |
+
assert tol
|
159 |
+
|
160 |
+
# Convert to fixed-point numbers. The dummy None is added so we can
|
161 |
+
# use 1-based indexing. (This just allows us to be consistent with
|
162 |
+
# Bailey's indexing. The algorithm is 100 lines long, so debugging
|
163 |
+
# a single wrong index can be painful.)
|
164 |
+
x = [None] + [ctx.to_fixed(ctx.mpf(xk), prec) for xk in x]
|
165 |
+
|
166 |
+
# Sanity check on magnitudes
|
167 |
+
minx = min(abs(xx) for xx in x[1:])
|
168 |
+
if not minx:
|
169 |
+
raise ValueError("PSLQ requires a vector of nonzero numbers")
|
170 |
+
if minx < tol//100:
|
171 |
+
if verbose:
|
172 |
+
print("STOPPING: (one number is too small)")
|
173 |
+
return None
|
174 |
+
|
175 |
+
g = sqrt_fixed((4<<prec)//3, prec)
|
176 |
+
A = {}
|
177 |
+
B = {}
|
178 |
+
H = {}
|
179 |
+
# Initialization
|
180 |
+
# step 1
|
181 |
+
for i in xrange(1, n+1):
|
182 |
+
for j in xrange(1, n+1):
|
183 |
+
A[i,j] = B[i,j] = (i==j) << prec
|
184 |
+
H[i,j] = 0
|
185 |
+
# step 2
|
186 |
+
s = [None] + [0] * n
|
187 |
+
for k in xrange(1, n+1):
|
188 |
+
t = 0
|
189 |
+
for j in xrange(k, n+1):
|
190 |
+
t += (x[j]**2 >> prec)
|
191 |
+
s[k] = sqrt_fixed(t, prec)
|
192 |
+
t = s[1]
|
193 |
+
y = x[:]
|
194 |
+
for k in xrange(1, n+1):
|
195 |
+
y[k] = (x[k] << prec) // t
|
196 |
+
s[k] = (s[k] << prec) // t
|
197 |
+
# step 3
|
198 |
+
for i in xrange(1, n+1):
|
199 |
+
for j in xrange(i+1, n):
|
200 |
+
H[i,j] = 0
|
201 |
+
if i <= n-1:
|
202 |
+
if s[i]:
|
203 |
+
H[i,i] = (s[i+1] << prec) // s[i]
|
204 |
+
else:
|
205 |
+
H[i,i] = 0
|
206 |
+
for j in range(1, i):
|
207 |
+
sjj1 = s[j]*s[j+1]
|
208 |
+
if sjj1:
|
209 |
+
H[i,j] = ((-y[i]*y[j])<<prec)//sjj1
|
210 |
+
else:
|
211 |
+
H[i,j] = 0
|
212 |
+
# step 4
|
213 |
+
for i in xrange(2, n+1):
|
214 |
+
for j in xrange(i-1, 0, -1):
|
215 |
+
#t = floor(H[i,j]/H[j,j] + 0.5)
|
216 |
+
if H[j,j]:
|
217 |
+
t = round_fixed((H[i,j] << prec)//H[j,j], prec)
|
218 |
+
else:
|
219 |
+
#t = 0
|
220 |
+
continue
|
221 |
+
y[j] = y[j] + (t*y[i] >> prec)
|
222 |
+
for k in xrange(1, j+1):
|
223 |
+
H[i,k] = H[i,k] - (t*H[j,k] >> prec)
|
224 |
+
for k in xrange(1, n+1):
|
225 |
+
A[i,k] = A[i,k] - (t*A[j,k] >> prec)
|
226 |
+
B[k,j] = B[k,j] + (t*B[k,i] >> prec)
|
227 |
+
# Main algorithm
|
228 |
+
for REP in range(maxsteps):
|
229 |
+
# Step 1
|
230 |
+
m = -1
|
231 |
+
szmax = -1
|
232 |
+
for i in range(1, n):
|
233 |
+
h = H[i,i]
|
234 |
+
sz = (g**i * abs(h)) >> (prec*(i-1))
|
235 |
+
if sz > szmax:
|
236 |
+
m = i
|
237 |
+
szmax = sz
|
238 |
+
# Step 2
|
239 |
+
y[m], y[m+1] = y[m+1], y[m]
|
240 |
+
for i in xrange(1,n+1): H[m,i], H[m+1,i] = H[m+1,i], H[m,i]
|
241 |
+
for i in xrange(1,n+1): A[m,i], A[m+1,i] = A[m+1,i], A[m,i]
|
242 |
+
for i in xrange(1,n+1): B[i,m], B[i,m+1] = B[i,m+1], B[i,m]
|
243 |
+
# Step 3
|
244 |
+
if m <= n - 2:
|
245 |
+
t0 = sqrt_fixed((H[m,m]**2 + H[m,m+1]**2)>>prec, prec)
|
246 |
+
# A zero element probably indicates that the precision has
|
247 |
+
# been exhausted. XXX: this could be spurious, due to
|
248 |
+
# using fixed-point arithmetic
|
249 |
+
if not t0:
|
250 |
+
break
|
251 |
+
t1 = (H[m,m] << prec) // t0
|
252 |
+
t2 = (H[m,m+1] << prec) // t0
|
253 |
+
for i in xrange(m, n+1):
|
254 |
+
t3 = H[i,m]
|
255 |
+
t4 = H[i,m+1]
|
256 |
+
H[i,m] = (t1*t3+t2*t4) >> prec
|
257 |
+
H[i,m+1] = (-t2*t3+t1*t4) >> prec
|
258 |
+
# Step 4
|
259 |
+
for i in xrange(m+1, n+1):
|
260 |
+
for j in xrange(min(i-1, m+1), 0, -1):
|
261 |
+
try:
|
262 |
+
t = round_fixed((H[i,j] << prec)//H[j,j], prec)
|
263 |
+
# Precision probably exhausted
|
264 |
+
except ZeroDivisionError:
|
265 |
+
break
|
266 |
+
y[j] = y[j] + ((t*y[i]) >> prec)
|
267 |
+
for k in xrange(1, j+1):
|
268 |
+
H[i,k] = H[i,k] - (t*H[j,k] >> prec)
|
269 |
+
for k in xrange(1, n+1):
|
270 |
+
A[i,k] = A[i,k] - (t*A[j,k] >> prec)
|
271 |
+
B[k,j] = B[k,j] + (t*B[k,i] >> prec)
|
272 |
+
# Until a relation is found, the error typically decreases
|
273 |
+
# slowly (e.g. a factor 1-10) with each step TODO: we could
|
274 |
+
# compare err from two successive iterations. If there is a
|
275 |
+
# large drop (several orders of magnitude), that indicates a
|
276 |
+
# "high quality" relation was detected. Reporting this to
|
277 |
+
# the user somehow might be useful.
|
278 |
+
best_err = maxcoeff<<prec
|
279 |
+
for i in xrange(1, n+1):
|
280 |
+
err = abs(y[i])
|
281 |
+
# Maybe we are done?
|
282 |
+
if err < tol:
|
283 |
+
# We are done if the coefficients are acceptable
|
284 |
+
vec = [int(round_fixed(B[j,i], prec) >> prec) for j in \
|
285 |
+
range(1,n+1)]
|
286 |
+
if max(abs(v) for v in vec) < maxcoeff:
|
287 |
+
if verbose:
|
288 |
+
print("FOUND relation at iter %i/%i, error: %s" % \
|
289 |
+
(REP, maxsteps, ctx.nstr(err / ctx.mpf(2)**prec, 1)))
|
290 |
+
return vec
|
291 |
+
best_err = min(err, best_err)
|
292 |
+
# Calculate a lower bound for the norm. We could do this
|
293 |
+
# more exactly (using the Euclidean norm) but there is probably
|
294 |
+
# no practical benefit.
|
295 |
+
recnorm = max(abs(h) for h in H.values())
|
296 |
+
if recnorm:
|
297 |
+
norm = ((1 << (2*prec)) // recnorm) >> prec
|
298 |
+
norm //= 100
|
299 |
+
else:
|
300 |
+
norm = ctx.inf
|
301 |
+
if verbose:
|
302 |
+
print("%i/%i: Error: %8s Norm: %s" % \
|
303 |
+
(REP, maxsteps, ctx.nstr(best_err / ctx.mpf(2)**prec, 1), norm))
|
304 |
+
if norm >= maxcoeff:
|
305 |
+
break
|
306 |
+
if verbose:
|
307 |
+
print("CANCELLING after step %i/%i." % (REP, maxsteps))
|
308 |
+
print("Could not find an integer relation. Norm bound: %s" % norm)
|
309 |
+
return None
|
310 |
+
|
311 |
+
def findpoly(ctx, x, n=1, **kwargs):
|
312 |
+
r"""
|
313 |
+
``findpoly(x, n)`` returns the coefficients of an integer
|
314 |
+
polynomial `P` of degree at most `n` such that `P(x) \approx 0`.
|
315 |
+
If no polynomial having `x` as a root can be found,
|
316 |
+
:func:`~mpmath.findpoly` returns ``None``.
|
317 |
+
|
318 |
+
:func:`~mpmath.findpoly` works by successively calling :func:`~mpmath.pslq` with
|
319 |
+
the vectors `[1, x]`, `[1, x, x^2]`, `[1, x, x^2, x^3]`, ...,
|
320 |
+
`[1, x, x^2, .., x^n]` as input. Keyword arguments given to
|
321 |
+
:func:`~mpmath.findpoly` are forwarded verbatim to :func:`~mpmath.pslq`. In
|
322 |
+
particular, you can specify a tolerance for `P(x)` with ``tol``
|
323 |
+
and a maximum permitted coefficient size with ``maxcoeff``.
|
324 |
+
|
325 |
+
For large values of `n`, it is recommended to run :func:`~mpmath.findpoly`
|
326 |
+
at high precision; preferably 50 digits or more.
|
327 |
+
|
328 |
+
**Examples**
|
329 |
+
|
330 |
+
By default (degree `n = 1`), :func:`~mpmath.findpoly` simply finds a linear
|
331 |
+
polynomial with a rational root::
|
332 |
+
|
333 |
+
>>> from mpmath import *
|
334 |
+
>>> mp.dps = 15; mp.pretty = True
|
335 |
+
>>> findpoly(0.7)
|
336 |
+
[-10, 7]
|
337 |
+
|
338 |
+
The generated coefficient list is valid input to ``polyval`` and
|
339 |
+
``polyroots``::
|
340 |
+
|
341 |
+
>>> nprint(polyval(findpoly(phi, 2), phi), 1)
|
342 |
+
-2.0e-16
|
343 |
+
>>> for r in polyroots(findpoly(phi, 2)):
|
344 |
+
... print(r)
|
345 |
+
...
|
346 |
+
-0.618033988749895
|
347 |
+
1.61803398874989
|
348 |
+
|
349 |
+
Numbers of the form `m + n \sqrt p` for integers `(m, n, p)` are
|
350 |
+
solutions to quadratic equations. As we find here, `1+\sqrt 2`
|
351 |
+
is a root of the polynomial `x^2 - 2x - 1`::
|
352 |
+
|
353 |
+
>>> findpoly(1+sqrt(2), 2)
|
354 |
+
[1, -2, -1]
|
355 |
+
>>> findroot(lambda x: x**2 - 2*x - 1, 1)
|
356 |
+
2.4142135623731
|
357 |
+
|
358 |
+
Despite only containing square roots, the following number results
|
359 |
+
in a polynomial of degree 4::
|
360 |
+
|
361 |
+
>>> findpoly(sqrt(2)+sqrt(3), 4)
|
362 |
+
[1, 0, -10, 0, 1]
|
363 |
+
|
364 |
+
In fact, `x^4 - 10x^2 + 1` is the *minimal polynomial* of
|
365 |
+
`r = \sqrt 2 + \sqrt 3`, meaning that a rational polynomial of
|
366 |
+
lower degree having `r` as a root does not exist. Given sufficient
|
367 |
+
precision, :func:`~mpmath.findpoly` will usually find the correct
|
368 |
+
minimal polynomial of a given algebraic number.
|
369 |
+
|
370 |
+
**Non-algebraic numbers**
|
371 |
+
|
372 |
+
If :func:`~mpmath.findpoly` fails to find a polynomial with given
|
373 |
+
coefficient size and tolerance constraints, that means no such
|
374 |
+
polynomial exists.
|
375 |
+
|
376 |
+
We can verify that `\pi` is not an algebraic number of degree 3 with
|
377 |
+
coefficients less than 1000::
|
378 |
+
|
379 |
+
>>> mp.dps = 15
|
380 |
+
>>> findpoly(pi, 3)
|
381 |
+
>>>
|
382 |
+
|
383 |
+
It is always possible to find an algebraic approximation of a number
|
384 |
+
using one (or several) of the following methods:
|
385 |
+
|
386 |
+
1. Increasing the permitted degree
|
387 |
+
2. Allowing larger coefficients
|
388 |
+
3. Reducing the tolerance
|
389 |
+
|
390 |
+
One example of each method is shown below::
|
391 |
+
|
392 |
+
>>> mp.dps = 15
|
393 |
+
>>> findpoly(pi, 4)
|
394 |
+
[95, -545, 863, -183, -298]
|
395 |
+
>>> findpoly(pi, 3, maxcoeff=10000)
|
396 |
+
[836, -1734, -2658, -457]
|
397 |
+
>>> findpoly(pi, 3, tol=1e-7)
|
398 |
+
[-4, 22, -29, -2]
|
399 |
+
|
400 |
+
It is unknown whether Euler's constant is transcendental (or even
|
401 |
+
irrational). We can use :func:`~mpmath.findpoly` to check that if is
|
402 |
+
an algebraic number, its minimal polynomial must have degree
|
403 |
+
at least 7 and a coefficient of magnitude at least 1000000::
|
404 |
+
|
405 |
+
>>> mp.dps = 200
|
406 |
+
>>> findpoly(euler, 6, maxcoeff=10**6, tol=1e-100, maxsteps=1000)
|
407 |
+
>>>
|
408 |
+
|
409 |
+
Note that the high precision and strict tolerance is necessary
|
410 |
+
for such high-degree runs, since otherwise unwanted low-accuracy
|
411 |
+
approximations will be detected. It may also be necessary to set
|
412 |
+
maxsteps high to prevent a premature exit (before the coefficient
|
413 |
+
bound has been reached). Running with ``verbose=True`` to get an
|
414 |
+
idea what is happening can be useful.
|
415 |
+
"""
|
416 |
+
x = ctx.mpf(x)
|
417 |
+
if n < 1:
|
418 |
+
raise ValueError("n cannot be less than 1")
|
419 |
+
if x == 0:
|
420 |
+
return [1, 0]
|
421 |
+
xs = [ctx.mpf(1)]
|
422 |
+
for i in range(1,n+1):
|
423 |
+
xs.append(x**i)
|
424 |
+
a = ctx.pslq(xs, **kwargs)
|
425 |
+
if a is not None:
|
426 |
+
return a[::-1]
|
427 |
+
|
428 |
+
def fracgcd(p, q):
|
429 |
+
x, y = p, q
|
430 |
+
while y:
|
431 |
+
x, y = y, x % y
|
432 |
+
if x != 1:
|
433 |
+
p //= x
|
434 |
+
q //= x
|
435 |
+
if q == 1:
|
436 |
+
return p
|
437 |
+
return p, q
|
438 |
+
|
439 |
+
def pslqstring(r, constants):
|
440 |
+
q = r[0]
|
441 |
+
r = r[1:]
|
442 |
+
s = []
|
443 |
+
for i in range(len(r)):
|
444 |
+
p = r[i]
|
445 |
+
if p:
|
446 |
+
z = fracgcd(-p,q)
|
447 |
+
cs = constants[i][1]
|
448 |
+
if cs == '1':
|
449 |
+
cs = ''
|
450 |
+
else:
|
451 |
+
cs = '*' + cs
|
452 |
+
if isinstance(z, int_types):
|
453 |
+
if z > 0: term = str(z) + cs
|
454 |
+
else: term = ("(%s)" % z) + cs
|
455 |
+
else:
|
456 |
+
term = ("(%s/%s)" % z) + cs
|
457 |
+
s.append(term)
|
458 |
+
s = ' + '.join(s)
|
459 |
+
if '+' in s or '*' in s:
|
460 |
+
s = '(' + s + ')'
|
461 |
+
return s or '0'
|
462 |
+
|
463 |
+
def prodstring(r, constants):
|
464 |
+
q = r[0]
|
465 |
+
r = r[1:]
|
466 |
+
num = []
|
467 |
+
den = []
|
468 |
+
for i in range(len(r)):
|
469 |
+
p = r[i]
|
470 |
+
if p:
|
471 |
+
z = fracgcd(-p,q)
|
472 |
+
cs = constants[i][1]
|
473 |
+
if isinstance(z, int_types):
|
474 |
+
if abs(z) == 1: t = cs
|
475 |
+
else: t = '%s**%s' % (cs, abs(z))
|
476 |
+
([num,den][z<0]).append(t)
|
477 |
+
else:
|
478 |
+
t = '%s**(%s/%s)' % (cs, abs(z[0]), z[1])
|
479 |
+
([num,den][z[0]<0]).append(t)
|
480 |
+
num = '*'.join(num)
|
481 |
+
den = '*'.join(den)
|
482 |
+
if num and den: return "(%s)/(%s)" % (num, den)
|
483 |
+
if num: return num
|
484 |
+
if den: return "1/(%s)" % den
|
485 |
+
|
486 |
+
def quadraticstring(ctx,t,a,b,c):
|
487 |
+
if c < 0:
|
488 |
+
a,b,c = -a,-b,-c
|
489 |
+
u1 = (-b+ctx.sqrt(b**2-4*a*c))/(2*c)
|
490 |
+
u2 = (-b-ctx.sqrt(b**2-4*a*c))/(2*c)
|
491 |
+
if abs(u1-t) < abs(u2-t):
|
492 |
+
if b: s = '((%s+sqrt(%s))/%s)' % (-b,b**2-4*a*c,2*c)
|
493 |
+
else: s = '(sqrt(%s)/%s)' % (-4*a*c,2*c)
|
494 |
+
else:
|
495 |
+
if b: s = '((%s-sqrt(%s))/%s)' % (-b,b**2-4*a*c,2*c)
|
496 |
+
else: s = '(-sqrt(%s)/%s)' % (-4*a*c,2*c)
|
497 |
+
return s
|
498 |
+
|
499 |
+
# Transformation y = f(x,c), with inverse function x = f(y,c)
|
500 |
+
# The third entry indicates whether the transformation is
|
501 |
+
# redundant when c = 1
|
502 |
+
transforms = [
|
503 |
+
(lambda ctx,x,c: x*c, '$y/$c', 0),
|
504 |
+
(lambda ctx,x,c: x/c, '$c*$y', 1),
|
505 |
+
(lambda ctx,x,c: c/x, '$c/$y', 0),
|
506 |
+
(lambda ctx,x,c: (x*c)**2, 'sqrt($y)/$c', 0),
|
507 |
+
(lambda ctx,x,c: (x/c)**2, '$c*sqrt($y)', 1),
|
508 |
+
(lambda ctx,x,c: (c/x)**2, '$c/sqrt($y)', 0),
|
509 |
+
(lambda ctx,x,c: c*x**2, 'sqrt($y)/sqrt($c)', 1),
|
510 |
+
(lambda ctx,x,c: x**2/c, 'sqrt($c)*sqrt($y)', 1),
|
511 |
+
(lambda ctx,x,c: c/x**2, 'sqrt($c)/sqrt($y)', 1),
|
512 |
+
(lambda ctx,x,c: ctx.sqrt(x*c), '$y**2/$c', 0),
|
513 |
+
(lambda ctx,x,c: ctx.sqrt(x/c), '$c*$y**2', 1),
|
514 |
+
(lambda ctx,x,c: ctx.sqrt(c/x), '$c/$y**2', 0),
|
515 |
+
(lambda ctx,x,c: c*ctx.sqrt(x), '$y**2/$c**2', 1),
|
516 |
+
(lambda ctx,x,c: ctx.sqrt(x)/c, '$c**2*$y**2', 1),
|
517 |
+
(lambda ctx,x,c: c/ctx.sqrt(x), '$c**2/$y**2', 1),
|
518 |
+
(lambda ctx,x,c: ctx.exp(x*c), 'log($y)/$c', 0),
|
519 |
+
(lambda ctx,x,c: ctx.exp(x/c), '$c*log($y)', 1),
|
520 |
+
(lambda ctx,x,c: ctx.exp(c/x), '$c/log($y)', 0),
|
521 |
+
(lambda ctx,x,c: c*ctx.exp(x), 'log($y/$c)', 1),
|
522 |
+
(lambda ctx,x,c: ctx.exp(x)/c, 'log($c*$y)', 1),
|
523 |
+
(lambda ctx,x,c: c/ctx.exp(x), 'log($c/$y)', 0),
|
524 |
+
(lambda ctx,x,c: ctx.ln(x*c), 'exp($y)/$c', 0),
|
525 |
+
(lambda ctx,x,c: ctx.ln(x/c), '$c*exp($y)', 1),
|
526 |
+
(lambda ctx,x,c: ctx.ln(c/x), '$c/exp($y)', 0),
|
527 |
+
(lambda ctx,x,c: c*ctx.ln(x), 'exp($y/$c)', 1),
|
528 |
+
(lambda ctx,x,c: ctx.ln(x)/c, 'exp($c*$y)', 1),
|
529 |
+
(lambda ctx,x,c: c/ctx.ln(x), 'exp($c/$y)', 0),
|
530 |
+
]
|
531 |
+
|
532 |
+
def identify(ctx, x, constants=[], tol=None, maxcoeff=1000, full=False,
|
533 |
+
verbose=False):
|
534 |
+
r"""
|
535 |
+
Given a real number `x`, ``identify(x)`` attempts to find an exact
|
536 |
+
formula for `x`. This formula is returned as a string. If no match
|
537 |
+
is found, ``None`` is returned. With ``full=True``, a list of
|
538 |
+
matching formulas is returned.
|
539 |
+
|
540 |
+
As a simple example, :func:`~mpmath.identify` will find an algebraic
|
541 |
+
formula for the golden ratio::
|
542 |
+
|
543 |
+
>>> from mpmath import *
|
544 |
+
>>> mp.dps = 15; mp.pretty = True
|
545 |
+
>>> identify(phi)
|
546 |
+
'((1+sqrt(5))/2)'
|
547 |
+
|
548 |
+
:func:`~mpmath.identify` can identify simple algebraic numbers and simple
|
549 |
+
combinations of given base constants, as well as certain basic
|
550 |
+
transformations thereof. More specifically, :func:`~mpmath.identify`
|
551 |
+
looks for the following:
|
552 |
+
|
553 |
+
1. Fractions
|
554 |
+
2. Quadratic algebraic numbers
|
555 |
+
3. Rational linear combinations of the base constants
|
556 |
+
4. Any of the above after first transforming `x` into `f(x)` where
|
557 |
+
`f(x)` is `1/x`, `\sqrt x`, `x^2`, `\log x` or `\exp x`, either
|
558 |
+
directly or with `x` or `f(x)` multiplied or divided by one of
|
559 |
+
the base constants
|
560 |
+
5. Products of fractional powers of the base constants and
|
561 |
+
small integers
|
562 |
+
|
563 |
+
Base constants can be given as a list of strings representing mpmath
|
564 |
+
expressions (:func:`~mpmath.identify` will ``eval`` the strings to numerical
|
565 |
+
values and use the original strings for the output), or as a dict of
|
566 |
+
formula:value pairs.
|
567 |
+
|
568 |
+
In order not to produce spurious results, :func:`~mpmath.identify` should
|
569 |
+
be used with high precision; preferably 50 digits or more.
|
570 |
+
|
571 |
+
**Examples**
|
572 |
+
|
573 |
+
Simple identifications can be performed safely at standard
|
574 |
+
precision. Here the default recognition of rational, algebraic,
|
575 |
+
and exp/log of algebraic numbers is demonstrated::
|
576 |
+
|
577 |
+
>>> mp.dps = 15
|
578 |
+
>>> identify(0.22222222222222222)
|
579 |
+
'(2/9)'
|
580 |
+
>>> identify(1.9662210973805663)
|
581 |
+
'sqrt(((24+sqrt(48))/8))'
|
582 |
+
>>> identify(4.1132503787829275)
|
583 |
+
'exp((sqrt(8)/2))'
|
584 |
+
>>> identify(0.881373587019543)
|
585 |
+
'log(((2+sqrt(8))/2))'
|
586 |
+
|
587 |
+
By default, :func:`~mpmath.identify` does not recognize `\pi`. At standard
|
588 |
+
precision it finds a not too useful approximation. At slightly
|
589 |
+
increased precision, this approximation is no longer accurate
|
590 |
+
enough and :func:`~mpmath.identify` more correctly returns ``None``::
|
591 |
+
|
592 |
+
>>> identify(pi)
|
593 |
+
'(2**(176/117)*3**(20/117)*5**(35/39))/(7**(92/117))'
|
594 |
+
>>> mp.dps = 30
|
595 |
+
>>> identify(pi)
|
596 |
+
>>>
|
597 |
+
|
598 |
+
Numbers such as `\pi`, and simple combinations of user-defined
|
599 |
+
constants, can be identified if they are provided explicitly::
|
600 |
+
|
601 |
+
>>> identify(3*pi-2*e, ['pi', 'e'])
|
602 |
+
'(3*pi + (-2)*e)'
|
603 |
+
|
604 |
+
Here is an example using a dict of constants. Note that the
|
605 |
+
constants need not be "atomic"; :func:`~mpmath.identify` can just
|
606 |
+
as well express the given number in terms of expressions
|
607 |
+
given by formulas::
|
608 |
+
|
609 |
+
>>> identify(pi+e, {'a':pi+2, 'b':2*e})
|
610 |
+
'((-2) + 1*a + (1/2)*b)'
|
611 |
+
|
612 |
+
Next, we attempt some identifications with a set of base constants.
|
613 |
+
It is necessary to increase the precision a bit.
|
614 |
+
|
615 |
+
>>> mp.dps = 50
|
616 |
+
>>> base = ['sqrt(2)','pi','log(2)']
|
617 |
+
>>> identify(0.25, base)
|
618 |
+
'(1/4)'
|
619 |
+
>>> identify(3*pi + 2*sqrt(2) + 5*log(2)/7, base)
|
620 |
+
'(2*sqrt(2) + 3*pi + (5/7)*log(2))'
|
621 |
+
>>> identify(exp(pi+2), base)
|
622 |
+
'exp((2 + 1*pi))'
|
623 |
+
>>> identify(1/(3+sqrt(2)), base)
|
624 |
+
'((3/7) + (-1/7)*sqrt(2))'
|
625 |
+
>>> identify(sqrt(2)/(3*pi+4), base)
|
626 |
+
'sqrt(2)/(4 + 3*pi)'
|
627 |
+
>>> identify(5**(mpf(1)/3)*pi*log(2)**2, base)
|
628 |
+
'5**(1/3)*pi*log(2)**2'
|
629 |
+
|
630 |
+
An example of an erroneous solution being found when too low
|
631 |
+
precision is used::
|
632 |
+
|
633 |
+
>>> mp.dps = 15
|
634 |
+
>>> identify(1/(3*pi-4*e+sqrt(8)), ['pi', 'e', 'sqrt(2)'])
|
635 |
+
'((11/25) + (-158/75)*pi + (76/75)*e + (44/15)*sqrt(2))'
|
636 |
+
>>> mp.dps = 50
|
637 |
+
>>> identify(1/(3*pi-4*e+sqrt(8)), ['pi', 'e', 'sqrt(2)'])
|
638 |
+
'1/(3*pi + (-4)*e + 2*sqrt(2))'
|
639 |
+
|
640 |
+
**Finding approximate solutions**
|
641 |
+
|
642 |
+
The tolerance ``tol`` defaults to 3/4 of the working precision.
|
643 |
+
Lowering the tolerance is useful for finding approximate matches.
|
644 |
+
We can for example try to generate approximations for pi::
|
645 |
+
|
646 |
+
>>> mp.dps = 15
|
647 |
+
>>> identify(pi, tol=1e-2)
|
648 |
+
'(22/7)'
|
649 |
+
>>> identify(pi, tol=1e-3)
|
650 |
+
'(355/113)'
|
651 |
+
>>> identify(pi, tol=1e-10)
|
652 |
+
'(5**(339/269))/(2**(64/269)*3**(13/269)*7**(92/269))'
|
653 |
+
|
654 |
+
With ``full=True``, and by supplying a few base constants,
|
655 |
+
``identify`` can generate almost endless lists of approximations
|
656 |
+
for any number (the output below has been truncated to show only
|
657 |
+
the first few)::
|
658 |
+
|
659 |
+
>>> for p in identify(pi, ['e', 'catalan'], tol=1e-5, full=True):
|
660 |
+
... print(p)
|
661 |
+
... # doctest: +ELLIPSIS
|
662 |
+
e/log((6 + (-4/3)*e))
|
663 |
+
(3**3*5*e*catalan**2)/(2*7**2)
|
664 |
+
sqrt(((-13) + 1*e + 22*catalan))
|
665 |
+
log(((-6) + 24*e + 4*catalan)/e)
|
666 |
+
exp(catalan*((-1/5) + (8/15)*e))
|
667 |
+
catalan*(6 + (-6)*e + 15*catalan)
|
668 |
+
sqrt((5 + 26*e + (-3)*catalan))/e
|
669 |
+
e*sqrt(((-27) + 2*e + 25*catalan))
|
670 |
+
log(((-1) + (-11)*e + 59*catalan))
|
671 |
+
((3/20) + (21/20)*e + (3/20)*catalan)
|
672 |
+
...
|
673 |
+
|
674 |
+
The numerical values are roughly as close to `\pi` as permitted by the
|
675 |
+
specified tolerance:
|
676 |
+
|
677 |
+
>>> e/log(6-4*e/3)
|
678 |
+
3.14157719846001
|
679 |
+
>>> 135*e*catalan**2/98
|
680 |
+
3.14166950419369
|
681 |
+
>>> sqrt(e-13+22*catalan)
|
682 |
+
3.14158000062992
|
683 |
+
>>> log(24*e-6+4*catalan)-1
|
684 |
+
3.14158791577159
|
685 |
+
|
686 |
+
**Symbolic processing**
|
687 |
+
|
688 |
+
The output formula can be evaluated as a Python expression.
|
689 |
+
Note however that if fractions (like '2/3') are present in
|
690 |
+
the formula, Python's :func:`~mpmath.eval()` may erroneously perform
|
691 |
+
integer division. Note also that the output is not necessarily
|
692 |
+
in the algebraically simplest form::
|
693 |
+
|
694 |
+
>>> identify(sqrt(2))
|
695 |
+
'(sqrt(8)/2)'
|
696 |
+
|
697 |
+
As a solution to both problems, consider using SymPy's
|
698 |
+
:func:`~mpmath.sympify` to convert the formula into a symbolic expression.
|
699 |
+
SymPy can be used to pretty-print or further simplify the formula
|
700 |
+
symbolically::
|
701 |
+
|
702 |
+
>>> from sympy import sympify # doctest: +SKIP
|
703 |
+
>>> sympify(identify(sqrt(2))) # doctest: +SKIP
|
704 |
+
2**(1/2)
|
705 |
+
|
706 |
+
Sometimes :func:`~mpmath.identify` can simplify an expression further than
|
707 |
+
a symbolic algorithm::
|
708 |
+
|
709 |
+
>>> from sympy import simplify # doctest: +SKIP
|
710 |
+
>>> x = sympify('-1/(-3/2+(1/2)*5**(1/2))*(3/2-1/2*5**(1/2))**(1/2)') # doctest: +SKIP
|
711 |
+
>>> x # doctest: +SKIP
|
712 |
+
(3/2 - 5**(1/2)/2)**(-1/2)
|
713 |
+
>>> x = simplify(x) # doctest: +SKIP
|
714 |
+
>>> x # doctest: +SKIP
|
715 |
+
2/(6 - 2*5**(1/2))**(1/2)
|
716 |
+
>>> mp.dps = 30 # doctest: +SKIP
|
717 |
+
>>> x = sympify(identify(x.evalf(30))) # doctest: +SKIP
|
718 |
+
>>> x # doctest: +SKIP
|
719 |
+
1/2 + 5**(1/2)/2
|
720 |
+
|
721 |
+
(In fact, this functionality is available directly in SymPy as the
|
722 |
+
function :func:`~mpmath.nsimplify`, which is essentially a wrapper for
|
723 |
+
:func:`~mpmath.identify`.)
|
724 |
+
|
725 |
+
**Miscellaneous issues and limitations**
|
726 |
+
|
727 |
+
The input `x` must be a real number. All base constants must be
|
728 |
+
positive real numbers and must not be rationals or rational linear
|
729 |
+
combinations of each other.
|
730 |
+
|
731 |
+
The worst-case computation time grows quickly with the number of
|
732 |
+
base constants. Already with 3 or 4 base constants,
|
733 |
+
:func:`~mpmath.identify` may require several seconds to finish. To search
|
734 |
+
for relations among a large number of constants, you should
|
735 |
+
consider using :func:`~mpmath.pslq` directly.
|
736 |
+
|
737 |
+
The extended transformations are applied to x, not the constants
|
738 |
+
separately. As a result, ``identify`` will for example be able to
|
739 |
+
recognize ``exp(2*pi+3)`` with ``pi`` given as a base constant, but
|
740 |
+
not ``2*exp(pi)+3``. It will be able to recognize the latter if
|
741 |
+
``exp(pi)`` is given explicitly as a base constant.
|
742 |
+
|
743 |
+
"""
|
744 |
+
|
745 |
+
solutions = []
|
746 |
+
|
747 |
+
def addsolution(s):
|
748 |
+
if verbose: print("Found: ", s)
|
749 |
+
solutions.append(s)
|
750 |
+
|
751 |
+
x = ctx.mpf(x)
|
752 |
+
|
753 |
+
# Further along, x will be assumed positive
|
754 |
+
if x == 0:
|
755 |
+
if full: return ['0']
|
756 |
+
else: return '0'
|
757 |
+
if x < 0:
|
758 |
+
sol = ctx.identify(-x, constants, tol, maxcoeff, full, verbose)
|
759 |
+
if sol is None:
|
760 |
+
return sol
|
761 |
+
if full:
|
762 |
+
return ["-(%s)"%s for s in sol]
|
763 |
+
else:
|
764 |
+
return "-(%s)" % sol
|
765 |
+
|
766 |
+
if tol:
|
767 |
+
tol = ctx.mpf(tol)
|
768 |
+
else:
|
769 |
+
tol = ctx.eps**0.7
|
770 |
+
M = maxcoeff
|
771 |
+
|
772 |
+
if constants:
|
773 |
+
if isinstance(constants, dict):
|
774 |
+
constants = [(ctx.mpf(v), name) for (name, v) in sorted(constants.items())]
|
775 |
+
else:
|
776 |
+
namespace = dict((name, getattr(ctx,name)) for name in dir(ctx))
|
777 |
+
constants = [(eval(p, namespace), p) for p in constants]
|
778 |
+
else:
|
779 |
+
constants = []
|
780 |
+
|
781 |
+
# We always want to find at least rational terms
|
782 |
+
if 1 not in [value for (name, value) in constants]:
|
783 |
+
constants = [(ctx.mpf(1), '1')] + constants
|
784 |
+
|
785 |
+
# PSLQ with simple algebraic and functional transformations
|
786 |
+
for ft, ftn, red in transforms:
|
787 |
+
for c, cn in constants:
|
788 |
+
if red and cn == '1':
|
789 |
+
continue
|
790 |
+
t = ft(ctx,x,c)
|
791 |
+
# Prevent exponential transforms from wreaking havoc
|
792 |
+
if abs(t) > M**2 or abs(t) < tol:
|
793 |
+
continue
|
794 |
+
# Linear combination of base constants
|
795 |
+
r = ctx.pslq([t] + [a[0] for a in constants], tol, M)
|
796 |
+
s = None
|
797 |
+
if r is not None and max(abs(uw) for uw in r) <= M and r[0]:
|
798 |
+
s = pslqstring(r, constants)
|
799 |
+
# Quadratic algebraic numbers
|
800 |
+
else:
|
801 |
+
q = ctx.pslq([ctx.one, t, t**2], tol, M)
|
802 |
+
if q is not None and len(q) == 3 and q[2]:
|
803 |
+
aa, bb, cc = q
|
804 |
+
if max(abs(aa),abs(bb),abs(cc)) <= M:
|
805 |
+
s = quadraticstring(ctx,t,aa,bb,cc)
|
806 |
+
if s:
|
807 |
+
if cn == '1' and ('/$c' in ftn):
|
808 |
+
s = ftn.replace('$y', s).replace('/$c', '')
|
809 |
+
else:
|
810 |
+
s = ftn.replace('$y', s).replace('$c', cn)
|
811 |
+
addsolution(s)
|
812 |
+
if not full: return solutions[0]
|
813 |
+
|
814 |
+
if verbose:
|
815 |
+
print(".")
|
816 |
+
|
817 |
+
# Check for a direct multiplicative formula
|
818 |
+
if x != 1:
|
819 |
+
# Allow fractional powers of fractions
|
820 |
+
ilogs = [2,3,5,7]
|
821 |
+
# Watch out for existing fractional powers of fractions
|
822 |
+
logs = []
|
823 |
+
for a, s in constants:
|
824 |
+
if not sum(bool(ctx.findpoly(ctx.ln(a)/ctx.ln(i),1)) for i in ilogs):
|
825 |
+
logs.append((ctx.ln(a), s))
|
826 |
+
logs = [(ctx.ln(i),str(i)) for i in ilogs] + logs
|
827 |
+
r = ctx.pslq([ctx.ln(x)] + [a[0] for a in logs], tol, M)
|
828 |
+
if r is not None and max(abs(uw) for uw in r) <= M and r[0]:
|
829 |
+
addsolution(prodstring(r, logs))
|
830 |
+
if not full: return solutions[0]
|
831 |
+
|
832 |
+
if full:
|
833 |
+
return sorted(solutions, key=len)
|
834 |
+
else:
|
835 |
+
return None
|
836 |
+
|
837 |
+
IdentificationMethods.pslq = pslq
|
838 |
+
IdentificationMethods.findpoly = findpoly
|
839 |
+
IdentificationMethods.identify = identify
|
840 |
+
|
841 |
+
|
842 |
+
if __name__ == '__main__':
|
843 |
+
import doctest
|
844 |
+
doctest.testmod()
|
venv/lib/python3.10/site-packages/mpmath/math2.py
ADDED
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module complements the math and cmath builtin modules by providing
|
3 |
+
fast machine precision versions of some additional functions (gamma, ...)
|
4 |
+
and wrapping math/cmath functions so that they can be called with either
|
5 |
+
real or complex arguments.
|
6 |
+
"""
|
7 |
+
|
8 |
+
import operator
|
9 |
+
import math
|
10 |
+
import cmath
|
11 |
+
|
12 |
+
# Irrational (?) constants
|
13 |
+
pi = 3.1415926535897932385
|
14 |
+
e = 2.7182818284590452354
|
15 |
+
sqrt2 = 1.4142135623730950488
|
16 |
+
sqrt5 = 2.2360679774997896964
|
17 |
+
phi = 1.6180339887498948482
|
18 |
+
ln2 = 0.69314718055994530942
|
19 |
+
ln10 = 2.302585092994045684
|
20 |
+
euler = 0.57721566490153286061
|
21 |
+
catalan = 0.91596559417721901505
|
22 |
+
khinchin = 2.6854520010653064453
|
23 |
+
apery = 1.2020569031595942854
|
24 |
+
|
25 |
+
logpi = 1.1447298858494001741
|
26 |
+
|
27 |
+
def _mathfun_real(f_real, f_complex):
|
28 |
+
def f(x, **kwargs):
|
29 |
+
if type(x) is float:
|
30 |
+
return f_real(x)
|
31 |
+
if type(x) is complex:
|
32 |
+
return f_complex(x)
|
33 |
+
try:
|
34 |
+
x = float(x)
|
35 |
+
return f_real(x)
|
36 |
+
except (TypeError, ValueError):
|
37 |
+
x = complex(x)
|
38 |
+
return f_complex(x)
|
39 |
+
f.__name__ = f_real.__name__
|
40 |
+
return f
|
41 |
+
|
42 |
+
def _mathfun(f_real, f_complex):
|
43 |
+
def f(x, **kwargs):
|
44 |
+
if type(x) is complex:
|
45 |
+
return f_complex(x)
|
46 |
+
try:
|
47 |
+
return f_real(float(x))
|
48 |
+
except (TypeError, ValueError):
|
49 |
+
return f_complex(complex(x))
|
50 |
+
f.__name__ = f_real.__name__
|
51 |
+
return f
|
52 |
+
|
53 |
+
def _mathfun_n(f_real, f_complex):
|
54 |
+
def f(*args, **kwargs):
|
55 |
+
try:
|
56 |
+
return f_real(*(float(x) for x in args))
|
57 |
+
except (TypeError, ValueError):
|
58 |
+
return f_complex(*(complex(x) for x in args))
|
59 |
+
f.__name__ = f_real.__name__
|
60 |
+
return f
|
61 |
+
|
62 |
+
# Workaround for non-raising log and sqrt in Python 2.5 and 2.4
|
63 |
+
# on Unix system
|
64 |
+
try:
|
65 |
+
math.log(-2.0)
|
66 |
+
def math_log(x):
|
67 |
+
if x <= 0.0:
|
68 |
+
raise ValueError("math domain error")
|
69 |
+
return math.log(x)
|
70 |
+
def math_sqrt(x):
|
71 |
+
if x < 0.0:
|
72 |
+
raise ValueError("math domain error")
|
73 |
+
return math.sqrt(x)
|
74 |
+
except (ValueError, TypeError):
|
75 |
+
math_log = math.log
|
76 |
+
math_sqrt = math.sqrt
|
77 |
+
|
78 |
+
pow = _mathfun_n(operator.pow, lambda x, y: complex(x)**y)
|
79 |
+
log = _mathfun_n(math_log, cmath.log)
|
80 |
+
sqrt = _mathfun(math_sqrt, cmath.sqrt)
|
81 |
+
exp = _mathfun_real(math.exp, cmath.exp)
|
82 |
+
|
83 |
+
cos = _mathfun_real(math.cos, cmath.cos)
|
84 |
+
sin = _mathfun_real(math.sin, cmath.sin)
|
85 |
+
tan = _mathfun_real(math.tan, cmath.tan)
|
86 |
+
|
87 |
+
acos = _mathfun(math.acos, cmath.acos)
|
88 |
+
asin = _mathfun(math.asin, cmath.asin)
|
89 |
+
atan = _mathfun_real(math.atan, cmath.atan)
|
90 |
+
|
91 |
+
cosh = _mathfun_real(math.cosh, cmath.cosh)
|
92 |
+
sinh = _mathfun_real(math.sinh, cmath.sinh)
|
93 |
+
tanh = _mathfun_real(math.tanh, cmath.tanh)
|
94 |
+
|
95 |
+
floor = _mathfun_real(math.floor,
|
96 |
+
lambda z: complex(math.floor(z.real), math.floor(z.imag)))
|
97 |
+
ceil = _mathfun_real(math.ceil,
|
98 |
+
lambda z: complex(math.ceil(z.real), math.ceil(z.imag)))
|
99 |
+
|
100 |
+
|
101 |
+
cos_sin = _mathfun_real(lambda x: (math.cos(x), math.sin(x)),
|
102 |
+
lambda z: (cmath.cos(z), cmath.sin(z)))
|
103 |
+
|
104 |
+
cbrt = _mathfun(lambda x: x**(1./3), lambda z: z**(1./3))
|
105 |
+
|
106 |
+
def nthroot(x, n):
|
107 |
+
r = 1./n
|
108 |
+
try:
|
109 |
+
return float(x) ** r
|
110 |
+
except (ValueError, TypeError):
|
111 |
+
return complex(x) ** r
|
112 |
+
|
113 |
+
def _sinpi_real(x):
|
114 |
+
if x < 0:
|
115 |
+
return -_sinpi_real(-x)
|
116 |
+
n, r = divmod(x, 0.5)
|
117 |
+
r *= pi
|
118 |
+
n %= 4
|
119 |
+
if n == 0: return math.sin(r)
|
120 |
+
if n == 1: return math.cos(r)
|
121 |
+
if n == 2: return -math.sin(r)
|
122 |
+
if n == 3: return -math.cos(r)
|
123 |
+
|
124 |
+
def _cospi_real(x):
|
125 |
+
if x < 0:
|
126 |
+
x = -x
|
127 |
+
n, r = divmod(x, 0.5)
|
128 |
+
r *= pi
|
129 |
+
n %= 4
|
130 |
+
if n == 0: return math.cos(r)
|
131 |
+
if n == 1: return -math.sin(r)
|
132 |
+
if n == 2: return -math.cos(r)
|
133 |
+
if n == 3: return math.sin(r)
|
134 |
+
|
135 |
+
def _sinpi_complex(z):
|
136 |
+
if z.real < 0:
|
137 |
+
return -_sinpi_complex(-z)
|
138 |
+
n, r = divmod(z.real, 0.5)
|
139 |
+
z = pi*complex(r, z.imag)
|
140 |
+
n %= 4
|
141 |
+
if n == 0: return cmath.sin(z)
|
142 |
+
if n == 1: return cmath.cos(z)
|
143 |
+
if n == 2: return -cmath.sin(z)
|
144 |
+
if n == 3: return -cmath.cos(z)
|
145 |
+
|
146 |
+
def _cospi_complex(z):
|
147 |
+
if z.real < 0:
|
148 |
+
z = -z
|
149 |
+
n, r = divmod(z.real, 0.5)
|
150 |
+
z = pi*complex(r, z.imag)
|
151 |
+
n %= 4
|
152 |
+
if n == 0: return cmath.cos(z)
|
153 |
+
if n == 1: return -cmath.sin(z)
|
154 |
+
if n == 2: return -cmath.cos(z)
|
155 |
+
if n == 3: return cmath.sin(z)
|
156 |
+
|
157 |
+
cospi = _mathfun_real(_cospi_real, _cospi_complex)
|
158 |
+
sinpi = _mathfun_real(_sinpi_real, _sinpi_complex)
|
159 |
+
|
160 |
+
def tanpi(x):
|
161 |
+
try:
|
162 |
+
return sinpi(x) / cospi(x)
|
163 |
+
except OverflowError:
|
164 |
+
if complex(x).imag > 10:
|
165 |
+
return 1j
|
166 |
+
if complex(x).imag < 10:
|
167 |
+
return -1j
|
168 |
+
raise
|
169 |
+
|
170 |
+
def cotpi(x):
|
171 |
+
try:
|
172 |
+
return cospi(x) / sinpi(x)
|
173 |
+
except OverflowError:
|
174 |
+
if complex(x).imag > 10:
|
175 |
+
return -1j
|
176 |
+
if complex(x).imag < 10:
|
177 |
+
return 1j
|
178 |
+
raise
|
179 |
+
|
180 |
+
INF = 1e300*1e300
|
181 |
+
NINF = -INF
|
182 |
+
NAN = INF-INF
|
183 |
+
EPS = 2.2204460492503131e-16
|
184 |
+
|
185 |
+
_exact_gamma = (INF, 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0,
|
186 |
+
362880.0, 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
|
187 |
+
1307674368000.0, 20922789888000.0, 355687428096000.0, 6402373705728000.0,
|
188 |
+
121645100408832000.0, 2432902008176640000.0)
|
189 |
+
|
190 |
+
_max_exact_gamma = len(_exact_gamma)-1
|
191 |
+
|
192 |
+
# Lanczos coefficients used by the GNU Scientific Library
|
193 |
+
_lanczos_g = 7
|
194 |
+
_lanczos_p = (0.99999999999980993, 676.5203681218851, -1259.1392167224028,
|
195 |
+
771.32342877765313, -176.61502916214059, 12.507343278686905,
|
196 |
+
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7)
|
197 |
+
|
198 |
+
def _gamma_real(x):
|
199 |
+
_intx = int(x)
|
200 |
+
if _intx == x:
|
201 |
+
if _intx <= 0:
|
202 |
+
#return (-1)**_intx * INF
|
203 |
+
raise ZeroDivisionError("gamma function pole")
|
204 |
+
if _intx <= _max_exact_gamma:
|
205 |
+
return _exact_gamma[_intx]
|
206 |
+
if x < 0.5:
|
207 |
+
# TODO: sinpi
|
208 |
+
return pi / (_sinpi_real(x)*_gamma_real(1-x))
|
209 |
+
else:
|
210 |
+
x -= 1.0
|
211 |
+
r = _lanczos_p[0]
|
212 |
+
for i in range(1, _lanczos_g+2):
|
213 |
+
r += _lanczos_p[i]/(x+i)
|
214 |
+
t = x + _lanczos_g + 0.5
|
215 |
+
return 2.506628274631000502417 * t**(x+0.5) * math.exp(-t) * r
|
216 |
+
|
217 |
+
def _gamma_complex(x):
|
218 |
+
if not x.imag:
|
219 |
+
return complex(_gamma_real(x.real))
|
220 |
+
if x.real < 0.5:
|
221 |
+
# TODO: sinpi
|
222 |
+
return pi / (_sinpi_complex(x)*_gamma_complex(1-x))
|
223 |
+
else:
|
224 |
+
x -= 1.0
|
225 |
+
r = _lanczos_p[0]
|
226 |
+
for i in range(1, _lanczos_g+2):
|
227 |
+
r += _lanczos_p[i]/(x+i)
|
228 |
+
t = x + _lanczos_g + 0.5
|
229 |
+
return 2.506628274631000502417 * t**(x+0.5) * cmath.exp(-t) * r
|
230 |
+
|
231 |
+
gamma = _mathfun_real(_gamma_real, _gamma_complex)
|
232 |
+
|
233 |
+
def rgamma(x):
|
234 |
+
try:
|
235 |
+
return 1./gamma(x)
|
236 |
+
except ZeroDivisionError:
|
237 |
+
return x*0.0
|
238 |
+
|
239 |
+
def factorial(x):
|
240 |
+
return gamma(x+1.0)
|
241 |
+
|
242 |
+
def arg(x):
|
243 |
+
if type(x) is float:
|
244 |
+
return math.atan2(0.0,x)
|
245 |
+
return math.atan2(x.imag,x.real)
|
246 |
+
|
247 |
+
# XXX: broken for negatives
|
248 |
+
def loggamma(x):
|
249 |
+
if type(x) not in (float, complex):
|
250 |
+
try:
|
251 |
+
x = float(x)
|
252 |
+
except (ValueError, TypeError):
|
253 |
+
x = complex(x)
|
254 |
+
try:
|
255 |
+
xreal = x.real
|
256 |
+
ximag = x.imag
|
257 |
+
except AttributeError: # py2.5
|
258 |
+
xreal = x
|
259 |
+
ximag = 0.0
|
260 |
+
# Reflection formula
|
261 |
+
# http://functions.wolfram.com/GammaBetaErf/LogGamma/16/01/01/0003/
|
262 |
+
if xreal < 0.0:
|
263 |
+
if abs(x) < 0.5:
|
264 |
+
v = log(gamma(x))
|
265 |
+
if ximag == 0:
|
266 |
+
v = v.conjugate()
|
267 |
+
return v
|
268 |
+
z = 1-x
|
269 |
+
try:
|
270 |
+
re = z.real
|
271 |
+
im = z.imag
|
272 |
+
except AttributeError: # py2.5
|
273 |
+
re = z
|
274 |
+
im = 0.0
|
275 |
+
refloor = floor(re)
|
276 |
+
if im == 0.0:
|
277 |
+
imsign = 0
|
278 |
+
elif im < 0.0:
|
279 |
+
imsign = -1
|
280 |
+
else:
|
281 |
+
imsign = 1
|
282 |
+
return (-pi*1j)*abs(refloor)*(1-abs(imsign)) + logpi - \
|
283 |
+
log(sinpi(z-refloor)) - loggamma(z) + 1j*pi*refloor*imsign
|
284 |
+
if x == 1.0 or x == 2.0:
|
285 |
+
return x*0
|
286 |
+
p = 0.
|
287 |
+
while abs(x) < 11:
|
288 |
+
p -= log(x)
|
289 |
+
x += 1.0
|
290 |
+
s = 0.918938533204672742 + (x-0.5)*log(x) - x
|
291 |
+
r = 1./x
|
292 |
+
r2 = r*r
|
293 |
+
s += 0.083333333333333333333*r; r *= r2
|
294 |
+
s += -0.0027777777777777777778*r; r *= r2
|
295 |
+
s += 0.00079365079365079365079*r; r *= r2
|
296 |
+
s += -0.0005952380952380952381*r; r *= r2
|
297 |
+
s += 0.00084175084175084175084*r; r *= r2
|
298 |
+
s += -0.0019175269175269175269*r; r *= r2
|
299 |
+
s += 0.0064102564102564102564*r; r *= r2
|
300 |
+
s += -0.02955065359477124183*r
|
301 |
+
return s + p
|
302 |
+
|
303 |
+
_psi_coeff = [
|
304 |
+
0.083333333333333333333,
|
305 |
+
-0.0083333333333333333333,
|
306 |
+
0.003968253968253968254,
|
307 |
+
-0.0041666666666666666667,
|
308 |
+
0.0075757575757575757576,
|
309 |
+
-0.021092796092796092796,
|
310 |
+
0.083333333333333333333,
|
311 |
+
-0.44325980392156862745,
|
312 |
+
3.0539543302701197438,
|
313 |
+
-26.456212121212121212]
|
314 |
+
|
315 |
+
def _digamma_real(x):
|
316 |
+
_intx = int(x)
|
317 |
+
if _intx == x:
|
318 |
+
if _intx <= 0:
|
319 |
+
raise ZeroDivisionError("polygamma pole")
|
320 |
+
if x < 0.5:
|
321 |
+
x = 1.0-x
|
322 |
+
s = pi*cotpi(x)
|
323 |
+
else:
|
324 |
+
s = 0.0
|
325 |
+
while x < 10.0:
|
326 |
+
s -= 1.0/x
|
327 |
+
x += 1.0
|
328 |
+
x2 = x**-2
|
329 |
+
t = x2
|
330 |
+
for c in _psi_coeff:
|
331 |
+
s -= c*t
|
332 |
+
if t < 1e-20:
|
333 |
+
break
|
334 |
+
t *= x2
|
335 |
+
return s + math_log(x) - 0.5/x
|
336 |
+
|
337 |
+
def _digamma_complex(x):
|
338 |
+
if not x.imag:
|
339 |
+
return complex(_digamma_real(x.real))
|
340 |
+
if x.real < 0.5:
|
341 |
+
x = 1.0-x
|
342 |
+
s = pi*cotpi(x)
|
343 |
+
else:
|
344 |
+
s = 0.0
|
345 |
+
while abs(x) < 10.0:
|
346 |
+
s -= 1.0/x
|
347 |
+
x += 1.0
|
348 |
+
x2 = x**-2
|
349 |
+
t = x2
|
350 |
+
for c in _psi_coeff:
|
351 |
+
s -= c*t
|
352 |
+
if abs(t) < 1e-20:
|
353 |
+
break
|
354 |
+
t *= x2
|
355 |
+
return s + cmath.log(x) - 0.5/x
|
356 |
+
|
357 |
+
digamma = _mathfun_real(_digamma_real, _digamma_complex)
|
358 |
+
|
359 |
+
# TODO: could implement complex erf and erfc here. Need
|
360 |
+
# to find an accurate method (avoiding cancellation)
|
361 |
+
# for approx. 1 < abs(x) < 9.
|
362 |
+
|
363 |
+
_erfc_coeff_P = [
|
364 |
+
1.0000000161203922312,
|
365 |
+
2.1275306946297962644,
|
366 |
+
2.2280433377390253297,
|
367 |
+
1.4695509105618423961,
|
368 |
+
0.66275911699770787537,
|
369 |
+
0.20924776504163751585,
|
370 |
+
0.045459713768411264339,
|
371 |
+
0.0063065951710717791934,
|
372 |
+
0.00044560259661560421715][::-1]
|
373 |
+
|
374 |
+
_erfc_coeff_Q = [
|
375 |
+
1.0000000000000000000,
|
376 |
+
3.2559100272784894318,
|
377 |
+
4.9019435608903239131,
|
378 |
+
4.4971472894498014205,
|
379 |
+
2.7845640601891186528,
|
380 |
+
1.2146026030046904138,
|
381 |
+
0.37647108453729465912,
|
382 |
+
0.080970149639040548613,
|
383 |
+
0.011178148899483545902,
|
384 |
+
0.00078981003831980423513][::-1]
|
385 |
+
|
386 |
+
def _polyval(coeffs, x):
|
387 |
+
p = coeffs[0]
|
388 |
+
for c in coeffs[1:]:
|
389 |
+
p = c + x*p
|
390 |
+
return p
|
391 |
+
|
392 |
+
def _erf_taylor(x):
|
393 |
+
# Taylor series assuming 0 <= x <= 1
|
394 |
+
x2 = x*x
|
395 |
+
s = t = x
|
396 |
+
n = 1
|
397 |
+
while abs(t) > 1e-17:
|
398 |
+
t *= x2/n
|
399 |
+
s -= t/(n+n+1)
|
400 |
+
n += 1
|
401 |
+
t *= x2/n
|
402 |
+
s += t/(n+n+1)
|
403 |
+
n += 1
|
404 |
+
return 1.1283791670955125739*s
|
405 |
+
|
406 |
+
def _erfc_mid(x):
|
407 |
+
# Rational approximation assuming 0 <= x <= 9
|
408 |
+
return exp(-x*x)*_polyval(_erfc_coeff_P,x)/_polyval(_erfc_coeff_Q,x)
|
409 |
+
|
410 |
+
def _erfc_asymp(x):
|
411 |
+
# Asymptotic expansion assuming x >= 9
|
412 |
+
x2 = x*x
|
413 |
+
v = exp(-x2)/x*0.56418958354775628695
|
414 |
+
r = t = 0.5 / x2
|
415 |
+
s = 1.0
|
416 |
+
for n in range(1,22,4):
|
417 |
+
s -= t
|
418 |
+
t *= r * (n+2)
|
419 |
+
s += t
|
420 |
+
t *= r * (n+4)
|
421 |
+
if abs(t) < 1e-17:
|
422 |
+
break
|
423 |
+
return s * v
|
424 |
+
|
425 |
+
def erf(x):
|
426 |
+
"""
|
427 |
+
erf of a real number.
|
428 |
+
"""
|
429 |
+
x = float(x)
|
430 |
+
if x != x:
|
431 |
+
return x
|
432 |
+
if x < 0.0:
|
433 |
+
return -erf(-x)
|
434 |
+
if x >= 1.0:
|
435 |
+
if x >= 6.0:
|
436 |
+
return 1.0
|
437 |
+
return 1.0 - _erfc_mid(x)
|
438 |
+
return _erf_taylor(x)
|
439 |
+
|
440 |
+
def erfc(x):
|
441 |
+
"""
|
442 |
+
erfc of a real number.
|
443 |
+
"""
|
444 |
+
x = float(x)
|
445 |
+
if x != x:
|
446 |
+
return x
|
447 |
+
if x < 0.0:
|
448 |
+
if x < -6.0:
|
449 |
+
return 2.0
|
450 |
+
return 2.0-erfc(-x)
|
451 |
+
if x > 9.0:
|
452 |
+
return _erfc_asymp(x)
|
453 |
+
if x >= 1.0:
|
454 |
+
return _erfc_mid(x)
|
455 |
+
return 1.0 - _erf_taylor(x)
|
456 |
+
|
457 |
+
gauss42 = [\
|
458 |
+
(0.99839961899006235, 0.0041059986046490839),
|
459 |
+
(-0.99839961899006235, 0.0041059986046490839),
|
460 |
+
(0.9915772883408609, 0.009536220301748501),
|
461 |
+
(-0.9915772883408609,0.009536220301748501),
|
462 |
+
(0.97934250806374812, 0.014922443697357493),
|
463 |
+
(-0.97934250806374812, 0.014922443697357493),
|
464 |
+
(0.96175936533820439,0.020227869569052644),
|
465 |
+
(-0.96175936533820439, 0.020227869569052644),
|
466 |
+
(0.93892355735498811, 0.025422959526113047),
|
467 |
+
(-0.93892355735498811,0.025422959526113047),
|
468 |
+
(0.91095972490412735, 0.030479240699603467),
|
469 |
+
(-0.91095972490412735, 0.030479240699603467),
|
470 |
+
(0.87802056981217269,0.03536907109759211),
|
471 |
+
(-0.87802056981217269, 0.03536907109759211),
|
472 |
+
(0.8402859832618168, 0.040065735180692258),
|
473 |
+
(-0.8402859832618168,0.040065735180692258),
|
474 |
+
(0.7979620532554873, 0.044543577771965874),
|
475 |
+
(-0.7979620532554873, 0.044543577771965874),
|
476 |
+
(0.75127993568948048,0.048778140792803244),
|
477 |
+
(-0.75127993568948048, 0.048778140792803244),
|
478 |
+
(0.70049459055617114, 0.052746295699174064),
|
479 |
+
(-0.70049459055617114,0.052746295699174064),
|
480 |
+
(0.64588338886924779, 0.056426369358018376),
|
481 |
+
(-0.64588338886924779, 0.056426369358018376),
|
482 |
+
(0.58774459748510932, 0.059798262227586649),
|
483 |
+
(-0.58774459748510932, 0.059798262227586649),
|
484 |
+
(0.5263957499311922, 0.062843558045002565),
|
485 |
+
(-0.5263957499311922, 0.062843558045002565),
|
486 |
+
(0.46217191207042191, 0.065545624364908975),
|
487 |
+
(-0.46217191207042191, 0.065545624364908975),
|
488 |
+
(0.39542385204297503, 0.067889703376521934),
|
489 |
+
(-0.39542385204297503, 0.067889703376521934),
|
490 |
+
(0.32651612446541151, 0.069862992492594159),
|
491 |
+
(-0.32651612446541151, 0.069862992492594159),
|
492 |
+
(0.25582507934287907, 0.071454714265170971),
|
493 |
+
(-0.25582507934287907, 0.071454714265170971),
|
494 |
+
(0.18373680656485453, 0.072656175243804091),
|
495 |
+
(-0.18373680656485453, 0.072656175243804091),
|
496 |
+
(0.11064502720851986, 0.073460813453467527),
|
497 |
+
(-0.11064502720851986, 0.073460813453467527),
|
498 |
+
(0.036948943165351772, 0.073864234232172879),
|
499 |
+
(-0.036948943165351772, 0.073864234232172879)]
|
500 |
+
|
501 |
+
EI_ASYMP_CONVERGENCE_RADIUS = 40.0
|
502 |
+
|
503 |
+
def ei_asymp(z, _e1=False):
|
504 |
+
r = 1./z
|
505 |
+
s = t = 1.0
|
506 |
+
k = 1
|
507 |
+
while 1:
|
508 |
+
t *= k*r
|
509 |
+
s += t
|
510 |
+
if abs(t) < 1e-16:
|
511 |
+
break
|
512 |
+
k += 1
|
513 |
+
v = s*exp(z)/z
|
514 |
+
if _e1:
|
515 |
+
if type(z) is complex:
|
516 |
+
zreal = z.real
|
517 |
+
zimag = z.imag
|
518 |
+
else:
|
519 |
+
zreal = z
|
520 |
+
zimag = 0.0
|
521 |
+
if zimag == 0.0 and zreal > 0.0:
|
522 |
+
v += pi*1j
|
523 |
+
else:
|
524 |
+
if type(z) is complex:
|
525 |
+
if z.imag > 0:
|
526 |
+
v += pi*1j
|
527 |
+
if z.imag < 0:
|
528 |
+
v -= pi*1j
|
529 |
+
return v
|
530 |
+
|
531 |
+
def ei_taylor(z, _e1=False):
|
532 |
+
s = t = z
|
533 |
+
k = 2
|
534 |
+
while 1:
|
535 |
+
t = t*z/k
|
536 |
+
term = t/k
|
537 |
+
if abs(term) < 1e-17:
|
538 |
+
break
|
539 |
+
s += term
|
540 |
+
k += 1
|
541 |
+
s += euler
|
542 |
+
if _e1:
|
543 |
+
s += log(-z)
|
544 |
+
else:
|
545 |
+
if type(z) is float or z.imag == 0.0:
|
546 |
+
s += math_log(abs(z))
|
547 |
+
else:
|
548 |
+
s += cmath.log(z)
|
549 |
+
return s
|
550 |
+
|
551 |
+
def ei(z, _e1=False):
|
552 |
+
typez = type(z)
|
553 |
+
if typez not in (float, complex):
|
554 |
+
try:
|
555 |
+
z = float(z)
|
556 |
+
typez = float
|
557 |
+
except (TypeError, ValueError):
|
558 |
+
z = complex(z)
|
559 |
+
typez = complex
|
560 |
+
if not z:
|
561 |
+
return -INF
|
562 |
+
absz = abs(z)
|
563 |
+
if absz > EI_ASYMP_CONVERGENCE_RADIUS:
|
564 |
+
return ei_asymp(z, _e1)
|
565 |
+
elif absz <= 2.0 or (typez is float and z > 0.0):
|
566 |
+
return ei_taylor(z, _e1)
|
567 |
+
# Integrate, starting from whichever is smaller of a Taylor
|
568 |
+
# series value or an asymptotic series value
|
569 |
+
if typez is complex and z.real > 0.0:
|
570 |
+
zref = z / absz
|
571 |
+
ref = ei_taylor(zref, _e1)
|
572 |
+
else:
|
573 |
+
zref = EI_ASYMP_CONVERGENCE_RADIUS * z / absz
|
574 |
+
ref = ei_asymp(zref, _e1)
|
575 |
+
C = (zref-z)*0.5
|
576 |
+
D = (zref+z)*0.5
|
577 |
+
s = 0.0
|
578 |
+
if type(z) is complex:
|
579 |
+
_exp = cmath.exp
|
580 |
+
else:
|
581 |
+
_exp = math.exp
|
582 |
+
for x,w in gauss42:
|
583 |
+
t = C*x+D
|
584 |
+
s += w*_exp(t)/t
|
585 |
+
ref -= C*s
|
586 |
+
return ref
|
587 |
+
|
588 |
+
def e1(z):
|
589 |
+
# hack to get consistent signs if the imaginary part if 0
|
590 |
+
# and signed
|
591 |
+
typez = type(z)
|
592 |
+
if type(z) not in (float, complex):
|
593 |
+
try:
|
594 |
+
z = float(z)
|
595 |
+
typez = float
|
596 |
+
except (TypeError, ValueError):
|
597 |
+
z = complex(z)
|
598 |
+
typez = complex
|
599 |
+
if typez is complex and not z.imag:
|
600 |
+
z = complex(z.real, 0.0)
|
601 |
+
# end hack
|
602 |
+
return -ei(-z, _e1=True)
|
603 |
+
|
604 |
+
_zeta_int = [\
|
605 |
+
-0.5,
|
606 |
+
0.0,
|
607 |
+
1.6449340668482264365,1.2020569031595942854,1.0823232337111381915,
|
608 |
+
1.0369277551433699263,1.0173430619844491397,1.0083492773819228268,
|
609 |
+
1.0040773561979443394,1.0020083928260822144,1.0009945751278180853,
|
610 |
+
1.0004941886041194646,1.0002460865533080483,1.0001227133475784891,
|
611 |
+
1.0000612481350587048,1.0000305882363070205,1.0000152822594086519,
|
612 |
+
1.0000076371976378998,1.0000038172932649998,1.0000019082127165539,
|
613 |
+
1.0000009539620338728,1.0000004769329867878,1.0000002384505027277,
|
614 |
+
1.0000001192199259653,1.0000000596081890513,1.0000000298035035147,
|
615 |
+
1.0000000149015548284]
|
616 |
+
|
617 |
+
_zeta_P = [-3.50000000087575873, -0.701274355654678147,
|
618 |
+
-0.0672313458590012612, -0.00398731457954257841,
|
619 |
+
-0.000160948723019303141, -4.67633010038383371e-6,
|
620 |
+
-1.02078104417700585e-7, -1.68030037095896287e-9,
|
621 |
+
-1.85231868742346722e-11][::-1]
|
622 |
+
|
623 |
+
_zeta_Q = [1.00000000000000000, -0.936552848762465319,
|
624 |
+
-0.0588835413263763741, -0.00441498861482948666,
|
625 |
+
-0.000143416758067432622, -5.10691659585090782e-6,
|
626 |
+
-9.58813053268913799e-8, -1.72963791443181972e-9,
|
627 |
+
-1.83527919681474132e-11][::-1]
|
628 |
+
|
629 |
+
_zeta_1 = [3.03768838606128127e-10, -1.21924525236601262e-8,
|
630 |
+
2.01201845887608893e-7, -1.53917240683468381e-6,
|
631 |
+
-5.09890411005967954e-7, 0.000122464707271619326,
|
632 |
+
-0.000905721539353130232, -0.00239315326074843037,
|
633 |
+
0.084239750013159168, 0.418938517907442414, 0.500000001921884009]
|
634 |
+
|
635 |
+
_zeta_0 = [-3.46092485016748794e-10, -6.42610089468292485e-9,
|
636 |
+
1.76409071536679773e-7, -1.47141263991560698e-6, -6.38880222546167613e-7,
|
637 |
+
0.000122641099800668209, -0.000905894913516772796, -0.00239303348507992713,
|
638 |
+
0.0842396947501199816, 0.418938533204660256, 0.500000000000000052]
|
639 |
+
|
640 |
+
def zeta(s):
|
641 |
+
"""
|
642 |
+
Riemann zeta function, real argument
|
643 |
+
"""
|
644 |
+
if not isinstance(s, (float, int)):
|
645 |
+
try:
|
646 |
+
s = float(s)
|
647 |
+
except (ValueError, TypeError):
|
648 |
+
try:
|
649 |
+
s = complex(s)
|
650 |
+
if not s.imag:
|
651 |
+
return complex(zeta(s.real))
|
652 |
+
except (ValueError, TypeError):
|
653 |
+
pass
|
654 |
+
raise NotImplementedError
|
655 |
+
if s == 1:
|
656 |
+
raise ValueError("zeta(1) pole")
|
657 |
+
if s >= 27:
|
658 |
+
return 1.0 + 2.0**(-s) + 3.0**(-s)
|
659 |
+
n = int(s)
|
660 |
+
if n == s:
|
661 |
+
if n >= 0:
|
662 |
+
return _zeta_int[n]
|
663 |
+
if not (n % 2):
|
664 |
+
return 0.0
|
665 |
+
if s <= 0.0:
|
666 |
+
return 2.**s*pi**(s-1)*_sinpi_real(0.5*s)*_gamma_real(1-s)*zeta(1-s)
|
667 |
+
if s <= 2.0:
|
668 |
+
if s <= 1.0:
|
669 |
+
return _polyval(_zeta_0,s)/(s-1)
|
670 |
+
return _polyval(_zeta_1,s)/(s-1)
|
671 |
+
z = _polyval(_zeta_P,s) / _polyval(_zeta_Q,s)
|
672 |
+
return 1.0 + 2.0**(-s) + 3.0**(-s) + 4.0**(-s)*z
|
venv/lib/python3.10/site-packages/mpmath/rational.py
ADDED
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import operator
|
2 |
+
import sys
|
3 |
+
from .libmp import int_types, mpf_hash, bitcount, from_man_exp, HASH_MODULUS
|
4 |
+
|
5 |
+
new = object.__new__
|
6 |
+
|
7 |
+
def create_reduced(p, q, _cache={}):
|
8 |
+
key = p, q
|
9 |
+
if key in _cache:
|
10 |
+
return _cache[key]
|
11 |
+
x, y = p, q
|
12 |
+
while y:
|
13 |
+
x, y = y, x % y
|
14 |
+
if x != 1:
|
15 |
+
p //= x
|
16 |
+
q //= x
|
17 |
+
v = new(mpq)
|
18 |
+
v._mpq_ = p, q
|
19 |
+
# Speedup integers, half-integers and other small fractions
|
20 |
+
if q <= 4 and abs(key[0]) < 100:
|
21 |
+
_cache[key] = v
|
22 |
+
return v
|
23 |
+
|
24 |
+
class mpq(object):
|
25 |
+
"""
|
26 |
+
Exact rational type, currently only intended for internal use.
|
27 |
+
"""
|
28 |
+
|
29 |
+
__slots__ = ["_mpq_"]
|
30 |
+
|
31 |
+
def __new__(cls, p, q=1):
|
32 |
+
if type(p) is tuple:
|
33 |
+
p, q = p
|
34 |
+
elif hasattr(p, '_mpq_'):
|
35 |
+
p, q = p._mpq_
|
36 |
+
return create_reduced(p, q)
|
37 |
+
|
38 |
+
def __repr__(s):
|
39 |
+
return "mpq(%s,%s)" % s._mpq_
|
40 |
+
|
41 |
+
def __str__(s):
|
42 |
+
return "(%s/%s)" % s._mpq_
|
43 |
+
|
44 |
+
def __int__(s):
|
45 |
+
a, b = s._mpq_
|
46 |
+
return a // b
|
47 |
+
|
48 |
+
def __nonzero__(s):
|
49 |
+
return bool(s._mpq_[0])
|
50 |
+
|
51 |
+
__bool__ = __nonzero__
|
52 |
+
|
53 |
+
def __hash__(s):
|
54 |
+
a, b = s._mpq_
|
55 |
+
if sys.version_info >= (3, 2):
|
56 |
+
inverse = pow(b, HASH_MODULUS-2, HASH_MODULUS)
|
57 |
+
if not inverse:
|
58 |
+
h = sys.hash_info.inf
|
59 |
+
else:
|
60 |
+
h = (abs(a) * inverse) % HASH_MODULUS
|
61 |
+
if a < 0: h = -h
|
62 |
+
if h == -1: h = -2
|
63 |
+
return h
|
64 |
+
else:
|
65 |
+
if b == 1:
|
66 |
+
return hash(a)
|
67 |
+
# Power of two: mpf compatible hash
|
68 |
+
if not (b & (b-1)):
|
69 |
+
return mpf_hash(from_man_exp(a, 1-bitcount(b)))
|
70 |
+
return hash((a,b))
|
71 |
+
|
72 |
+
def __eq__(s, t):
|
73 |
+
ttype = type(t)
|
74 |
+
if ttype is mpq:
|
75 |
+
return s._mpq_ == t._mpq_
|
76 |
+
if ttype in int_types:
|
77 |
+
a, b = s._mpq_
|
78 |
+
if b != 1:
|
79 |
+
return False
|
80 |
+
return a == t
|
81 |
+
return NotImplemented
|
82 |
+
|
83 |
+
def __ne__(s, t):
|
84 |
+
ttype = type(t)
|
85 |
+
if ttype is mpq:
|
86 |
+
return s._mpq_ != t._mpq_
|
87 |
+
if ttype in int_types:
|
88 |
+
a, b = s._mpq_
|
89 |
+
if b != 1:
|
90 |
+
return True
|
91 |
+
return a != t
|
92 |
+
return NotImplemented
|
93 |
+
|
94 |
+
def _cmp(s, t, op):
|
95 |
+
ttype = type(t)
|
96 |
+
if ttype in int_types:
|
97 |
+
a, b = s._mpq_
|
98 |
+
return op(a, t*b)
|
99 |
+
if ttype is mpq:
|
100 |
+
a, b = s._mpq_
|
101 |
+
c, d = t._mpq_
|
102 |
+
return op(a*d, b*c)
|
103 |
+
return NotImplementedError
|
104 |
+
|
105 |
+
def __lt__(s, t): return s._cmp(t, operator.lt)
|
106 |
+
def __le__(s, t): return s._cmp(t, operator.le)
|
107 |
+
def __gt__(s, t): return s._cmp(t, operator.gt)
|
108 |
+
def __ge__(s, t): return s._cmp(t, operator.ge)
|
109 |
+
|
110 |
+
def __abs__(s):
|
111 |
+
a, b = s._mpq_
|
112 |
+
if a >= 0:
|
113 |
+
return s
|
114 |
+
v = new(mpq)
|
115 |
+
v._mpq_ = -a, b
|
116 |
+
return v
|
117 |
+
|
118 |
+
def __neg__(s):
|
119 |
+
a, b = s._mpq_
|
120 |
+
v = new(mpq)
|
121 |
+
v._mpq_ = -a, b
|
122 |
+
return v
|
123 |
+
|
124 |
+
def __pos__(s):
|
125 |
+
return s
|
126 |
+
|
127 |
+
def __add__(s, t):
|
128 |
+
ttype = type(t)
|
129 |
+
if ttype is mpq:
|
130 |
+
a, b = s._mpq_
|
131 |
+
c, d = t._mpq_
|
132 |
+
return create_reduced(a*d+b*c, b*d)
|
133 |
+
if ttype in int_types:
|
134 |
+
a, b = s._mpq_
|
135 |
+
v = new(mpq)
|
136 |
+
v._mpq_ = a+b*t, b
|
137 |
+
return v
|
138 |
+
return NotImplemented
|
139 |
+
|
140 |
+
__radd__ = __add__
|
141 |
+
|
142 |
+
def __sub__(s, t):
|
143 |
+
ttype = type(t)
|
144 |
+
if ttype is mpq:
|
145 |
+
a, b = s._mpq_
|
146 |
+
c, d = t._mpq_
|
147 |
+
return create_reduced(a*d-b*c, b*d)
|
148 |
+
if ttype in int_types:
|
149 |
+
a, b = s._mpq_
|
150 |
+
v = new(mpq)
|
151 |
+
v._mpq_ = a-b*t, b
|
152 |
+
return v
|
153 |
+
return NotImplemented
|
154 |
+
|
155 |
+
def __rsub__(s, t):
|
156 |
+
ttype = type(t)
|
157 |
+
if ttype is mpq:
|
158 |
+
a, b = s._mpq_
|
159 |
+
c, d = t._mpq_
|
160 |
+
return create_reduced(b*c-a*d, b*d)
|
161 |
+
if ttype in int_types:
|
162 |
+
a, b = s._mpq_
|
163 |
+
v = new(mpq)
|
164 |
+
v._mpq_ = b*t-a, b
|
165 |
+
return v
|
166 |
+
return NotImplemented
|
167 |
+
|
168 |
+
def __mul__(s, t):
|
169 |
+
ttype = type(t)
|
170 |
+
if ttype is mpq:
|
171 |
+
a, b = s._mpq_
|
172 |
+
c, d = t._mpq_
|
173 |
+
return create_reduced(a*c, b*d)
|
174 |
+
if ttype in int_types:
|
175 |
+
a, b = s._mpq_
|
176 |
+
return create_reduced(a*t, b)
|
177 |
+
return NotImplemented
|
178 |
+
|
179 |
+
__rmul__ = __mul__
|
180 |
+
|
181 |
+
def __div__(s, t):
|
182 |
+
ttype = type(t)
|
183 |
+
if ttype is mpq:
|
184 |
+
a, b = s._mpq_
|
185 |
+
c, d = t._mpq_
|
186 |
+
return create_reduced(a*d, b*c)
|
187 |
+
if ttype in int_types:
|
188 |
+
a, b = s._mpq_
|
189 |
+
return create_reduced(a, b*t)
|
190 |
+
return NotImplemented
|
191 |
+
|
192 |
+
def __rdiv__(s, t):
|
193 |
+
ttype = type(t)
|
194 |
+
if ttype is mpq:
|
195 |
+
a, b = s._mpq_
|
196 |
+
c, d = t._mpq_
|
197 |
+
return create_reduced(b*c, a*d)
|
198 |
+
if ttype in int_types:
|
199 |
+
a, b = s._mpq_
|
200 |
+
return create_reduced(b*t, a)
|
201 |
+
return NotImplemented
|
202 |
+
|
203 |
+
def __pow__(s, t):
|
204 |
+
ttype = type(t)
|
205 |
+
if ttype in int_types:
|
206 |
+
a, b = s._mpq_
|
207 |
+
if t:
|
208 |
+
if t < 0:
|
209 |
+
a, b, t = b, a, -t
|
210 |
+
v = new(mpq)
|
211 |
+
v._mpq_ = a**t, b**t
|
212 |
+
return v
|
213 |
+
raise ZeroDivisionError
|
214 |
+
return NotImplemented
|
215 |
+
|
216 |
+
|
217 |
+
mpq_1 = mpq((1,1))
|
218 |
+
mpq_0 = mpq((0,1))
|
219 |
+
mpq_1_2 = mpq((1,2))
|
220 |
+
mpq_3_2 = mpq((3,2))
|
221 |
+
mpq_1_4 = mpq((1,4))
|
222 |
+
mpq_1_16 = mpq((1,16))
|
223 |
+
mpq_3_16 = mpq((3,16))
|
224 |
+
mpq_5_2 = mpq((5,2))
|
225 |
+
mpq_3_4 = mpq((3,4))
|
226 |
+
mpq_7_4 = mpq((7,4))
|
227 |
+
mpq_5_4 = mpq((5,4))
|
228 |
+
|
229 |
+
|
230 |
+
# Register with "numbers" ABC
|
231 |
+
# We do not subclass, hence we do not use the @abstractmethod checks. While
|
232 |
+
# this is less invasive it may turn out that we do not actually support
|
233 |
+
# parts of the expected interfaces. See
|
234 |
+
# http://docs.python.org/2/library/numbers.html for list of abstract
|
235 |
+
# methods.
|
236 |
+
try:
|
237 |
+
import numbers
|
238 |
+
numbers.Rational.register(mpq)
|
239 |
+
except ImportError:
|
240 |
+
pass
|