applied-ai-018 commited on
Commit
df5bf3b
·
verified ·
1 Parent(s): 53f70d9

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/__init__.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_base.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_fp.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_iv.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/identification.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/math2.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/rational.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/usertools.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/visualization.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/mpmath/ctx_base.py +494 -0
  12. env-llmeval/lib/python3.10/site-packages/mpmath/ctx_mp_python.py +1149 -0
  13. env-llmeval/lib/python3.10/site-packages/mpmath/identification.py +844 -0
  14. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/__init__.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/calculus.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen_symmetric.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/linalg.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/matrices.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/calculus.py +531 -0
  21. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/eigen.py +877 -0
  22. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/linalg.py +790 -0
  23. env-llmeval/lib/python3.10/site-packages/mpmath/matrices/matrices.py +1005 -0
  24. env-llmeval/lib/python3.10/site-packages/mpmath/visualization.py +313 -0
  25. env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/INSTALLER +1 -0
  26. env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/LICENSE +29 -0
  27. env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/METADATA +530 -0
  28. env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/RECORD +66 -0
  29. env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/WHEEL +8 -0
  30. env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/top_level.txt +1 -0
  31. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/__init__.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_cell.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_font.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_style.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler.cpython-310.pyc +0 -0
  36. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler_interface.cpython-310.pyc +0 -0
  37. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_theme.cpython-310.pyc +0 -0
  38. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/_cell.py +30 -0
  39. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/_style.py +376 -0
  40. env-llmeval/lib/python3.10/site-packages/pytablewriter/style/_theme.py +101 -0
  41. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/__init__.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_common.cpython-310.pyc +0 -0
  43. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_elasticsearch.cpython-310.pyc +0 -0
  44. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_interface.cpython-310.pyc +0 -0
  45. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_msgfy.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_null.cpython-310.pyc +0 -0
  47. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_table_writer.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/__init__.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_asciidoc.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_borderless.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (8.28 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_base.cpython-310.pyc ADDED
Binary file (16.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_fp.cpython-310.pyc ADDED
Binary file (7.82 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_iv.cpython-310.pyc ADDED
Binary file (20.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp.cpython-310.pyc ADDED
Binary file (43 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/identification.cpython-310.pyc ADDED
Binary file (28.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/math2.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/rational.cpython-310.pyc ADDED
Binary file (5.97 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/usertools.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/visualization.cpython-310.pyc ADDED
Binary file (9.71 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/ctx_base.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.__name__
493
+ f_cached.__doc__ = f.__doc__
494
+ return f_cached
env-llmeval/lib/python3.10/site-packages/mpmath/ctx_mp_python.py ADDED
@@ -0,0 +1,1149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #from ctx_base import StandardBaseContext
2
+
3
+ from .libmp.backend import basestring, exec_
4
+
5
+ from .libmp import (MPZ, MPZ_ZERO, MPZ_ONE, int_types, repr_dps,
6
+ round_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
env-llmeval/lib/python3.10/site-packages/mpmath/identification.py ADDED
@@ -0,0 +1,844 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (248 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/calculus.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen.cpython-310.pyc ADDED
Binary file (18.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/eigen_symmetric.cpython-310.pyc ADDED
Binary file (43.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/linalg.cpython-310.pyc ADDED
Binary file (23.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__pycache__/matrices.cpython-310.pyc ADDED
Binary file (28.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/calculus.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..libmp.backend import xrange
2
+
3
+ # TODO: should use diagonalization-based algorithms
4
+
5
+ class MatrixCalculusMethods(object):
6
+
7
+ def _exp_pade(ctx, a):
8
+ """
9
+ Exponential of a matrix using Pade approximants.
10
+
11
+ See G. H. Golub, C. F. van Loan 'Matrix Computations',
12
+ third Ed., page 572
13
+
14
+ TODO:
15
+ - find a good estimate for q
16
+ - reduce the number of matrix multiplications to improve
17
+ performance
18
+ """
19
+ def eps_pade(p):
20
+ return ctx.mpf(2)**(3-2*p) * \
21
+ ctx.factorial(p)**2/(ctx.factorial(2*p)**2 * (2*p + 1))
22
+ q = 4
23
+ extraq = 8
24
+ while 1:
25
+ if eps_pade(q) < ctx.eps:
26
+ break
27
+ q += 1
28
+ q += extraq
29
+ j = int(max(1, ctx.mag(ctx.mnorm(a,'inf'))))
30
+ extra = q
31
+ prec = ctx.prec
32
+ ctx.dps += extra + 3
33
+ try:
34
+ a = a/2**j
35
+ na = a.rows
36
+ den = ctx.eye(na)
37
+ num = ctx.eye(na)
38
+ x = ctx.eye(na)
39
+ c = ctx.mpf(1)
40
+ for k in range(1, q+1):
41
+ c *= ctx.mpf(q - k + 1)/((2*q - k + 1) * k)
42
+ x = a*x
43
+ cx = c*x
44
+ num += cx
45
+ den += (-1)**k * cx
46
+ f = ctx.lu_solve_mat(den, num)
47
+ for k in range(j):
48
+ f = f*f
49
+ finally:
50
+ ctx.prec = prec
51
+ return f*1
52
+
53
+ def expm(ctx, A, method='taylor'):
54
+ r"""
55
+ Computes the matrix exponential of a square matrix `A`, which is defined
56
+ by the power series
57
+
58
+ .. math ::
59
+
60
+ \exp(A) = I + A + \frac{A^2}{2!} + \frac{A^3}{3!} + \ldots
61
+
62
+ With method='taylor', the matrix exponential is computed
63
+ using the Taylor series. With method='pade', Pade approximants
64
+ are used instead.
65
+
66
+ **Examples**
67
+
68
+ Basic examples::
69
+
70
+ >>> from mpmath import *
71
+ >>> mp.dps = 15; mp.pretty = True
72
+ >>> expm(zeros(3))
73
+ [1.0 0.0 0.0]
74
+ [0.0 1.0 0.0]
75
+ [0.0 0.0 1.0]
76
+ >>> expm(eye(3))
77
+ [2.71828182845905 0.0 0.0]
78
+ [ 0.0 2.71828182845905 0.0]
79
+ [ 0.0 0.0 2.71828182845905]
80
+ >>> expm([[1,1,0],[1,0,1],[0,1,0]])
81
+ [ 3.86814500615414 2.26812870852145 0.841130841230196]
82
+ [ 2.26812870852145 2.44114713886289 1.42699786729125]
83
+ [0.841130841230196 1.42699786729125 1.6000162976327]
84
+ >>> expm([[1,1,0],[1,0,1],[0,1,0]], method='pade')
85
+ [ 3.86814500615414 2.26812870852145 0.841130841230196]
86
+ [ 2.26812870852145 2.44114713886289 1.42699786729125]
87
+ [0.841130841230196 1.42699786729125 1.6000162976327]
88
+ >>> expm([[1+j, 0], [1+j,1]])
89
+ [(1.46869393991589 + 2.28735528717884j) 0.0]
90
+ [ (1.03776739863568 + 3.536943175722j) (2.71828182845905 + 0.0j)]
91
+
92
+ Matrices with large entries are allowed::
93
+
94
+ >>> expm(matrix([[1,2],[2,3]])**25)
95
+ [5.65024064048415e+2050488462815550 9.14228140091932e+2050488462815550]
96
+ [9.14228140091932e+2050488462815550 1.47925220414035e+2050488462815551]
97
+
98
+ The identity `\exp(A+B) = \exp(A) \exp(B)` does not hold for
99
+ noncommuting matrices::
100
+
101
+ >>> A = hilbert(3)
102
+ >>> B = A + eye(3)
103
+ >>> chop(mnorm(A*B - B*A))
104
+ 0.0
105
+ >>> chop(mnorm(expm(A+B) - expm(A)*expm(B)))
106
+ 0.0
107
+ >>> B = A + ones(3)
108
+ >>> mnorm(A*B - B*A)
109
+ 1.8
110
+ >>> mnorm(expm(A+B) - expm(A)*expm(B))
111
+ 42.0927851137247
112
+
113
+ """
114
+ if method == 'pade':
115
+ prec = ctx.prec
116
+ try:
117
+ A = ctx.matrix(A)
118
+ ctx.prec += 2*A.rows
119
+ res = ctx._exp_pade(A)
120
+ finally:
121
+ ctx.prec = prec
122
+ return res
123
+ A = ctx.matrix(A)
124
+ prec = ctx.prec
125
+ j = int(max(1, ctx.mag(ctx.mnorm(A,'inf'))))
126
+ j += int(0.5*prec**0.5)
127
+ try:
128
+ ctx.prec += 10 + 2*j
129
+ tol = +ctx.eps
130
+ A = A/2**j
131
+ T = A
132
+ Y = A**0 + A
133
+ k = 2
134
+ while 1:
135
+ T *= A * (1/ctx.mpf(k))
136
+ if ctx.mnorm(T, 'inf') < tol:
137
+ break
138
+ Y += T
139
+ k += 1
140
+ for k in xrange(j):
141
+ Y = Y*Y
142
+ finally:
143
+ ctx.prec = prec
144
+ Y *= 1
145
+ return Y
146
+
147
+ def cosm(ctx, A):
148
+ r"""
149
+ Gives the cosine of a square matrix `A`, defined in analogy
150
+ with the matrix exponential.
151
+
152
+ Examples::
153
+
154
+ >>> from mpmath import *
155
+ >>> mp.dps = 15; mp.pretty = True
156
+ >>> X = eye(3)
157
+ >>> cosm(X)
158
+ [0.54030230586814 0.0 0.0]
159
+ [ 0.0 0.54030230586814 0.0]
160
+ [ 0.0 0.0 0.54030230586814]
161
+ >>> X = hilbert(3)
162
+ >>> cosm(X)
163
+ [ 0.424403834569555 -0.316643413047167 -0.221474945949293]
164
+ [-0.316643413047167 0.820646708837824 -0.127183694770039]
165
+ [-0.221474945949293 -0.127183694770039 0.909236687217541]
166
+ >>> X = matrix([[1+j,-2],[0,-j]])
167
+ >>> cosm(X)
168
+ [(0.833730025131149 - 0.988897705762865j) (1.07485840848393 - 0.17192140544213j)]
169
+ [ 0.0 (1.54308063481524 + 0.0j)]
170
+ """
171
+ B = 0.5 * (ctx.expm(A*ctx.j) + ctx.expm(A*(-ctx.j)))
172
+ if not sum(A.apply(ctx.im).apply(abs)):
173
+ B = B.apply(ctx.re)
174
+ return B
175
+
176
+ def sinm(ctx, A):
177
+ r"""
178
+ Gives the sine of a square matrix `A`, defined in analogy
179
+ with the matrix exponential.
180
+
181
+ Examples::
182
+
183
+ >>> from mpmath import *
184
+ >>> mp.dps = 15; mp.pretty = True
185
+ >>> X = eye(3)
186
+ >>> sinm(X)
187
+ [0.841470984807897 0.0 0.0]
188
+ [ 0.0 0.841470984807897 0.0]
189
+ [ 0.0 0.0 0.841470984807897]
190
+ >>> X = hilbert(3)
191
+ >>> sinm(X)
192
+ [0.711608512150994 0.339783913247439 0.220742837314741]
193
+ [0.339783913247439 0.244113865695532 0.187231271174372]
194
+ [0.220742837314741 0.187231271174372 0.155816730769635]
195
+ >>> X = matrix([[1+j,-2],[0,-j]])
196
+ >>> sinm(X)
197
+ [(1.29845758141598 + 0.634963914784736j) (-1.96751511930922 + 0.314700021761367j)]
198
+ [ 0.0 (0.0 - 1.1752011936438j)]
199
+ """
200
+ B = (-0.5j) * (ctx.expm(A*ctx.j) - ctx.expm(A*(-ctx.j)))
201
+ if not sum(A.apply(ctx.im).apply(abs)):
202
+ B = B.apply(ctx.re)
203
+ return B
204
+
205
+ def _sqrtm_rot(ctx, A, _may_rotate):
206
+ # If the iteration fails to converge, cheat by performing
207
+ # a rotation by a complex number
208
+ u = ctx.j**0.3
209
+ return ctx.sqrtm(u*A, _may_rotate) / ctx.sqrt(u)
210
+
211
+ def sqrtm(ctx, A, _may_rotate=2):
212
+ r"""
213
+ Computes a square root of the square matrix `A`, i.e. returns
214
+ a matrix `B = A^{1/2}` such that `B^2 = A`. The square root
215
+ of a matrix, if it exists, is not unique.
216
+
217
+ **Examples**
218
+
219
+ Square roots of some simple matrices::
220
+
221
+ >>> from mpmath import *
222
+ >>> mp.dps = 15; mp.pretty = True
223
+ >>> sqrtm([[1,0], [0,1]])
224
+ [1.0 0.0]
225
+ [0.0 1.0]
226
+ >>> sqrtm([[0,0], [0,0]])
227
+ [0.0 0.0]
228
+ [0.0 0.0]
229
+ >>> sqrtm([[2,0],[0,1]])
230
+ [1.4142135623731 0.0]
231
+ [ 0.0 1.0]
232
+ >>> sqrtm([[1,1],[1,0]])
233
+ [ (0.920442065259926 - 0.21728689675164j) (0.568864481005783 + 0.351577584254143j)]
234
+ [(0.568864481005783 + 0.351577584254143j) (0.351577584254143 - 0.568864481005783j)]
235
+ >>> sqrtm([[1,0],[0,1]])
236
+ [1.0 0.0]
237
+ [0.0 1.0]
238
+ >>> sqrtm([[-1,0],[0,1]])
239
+ [(0.0 - 1.0j) 0.0]
240
+ [ 0.0 (1.0 + 0.0j)]
241
+ >>> sqrtm([[j,0],[0,j]])
242
+ [(0.707106781186547 + 0.707106781186547j) 0.0]
243
+ [ 0.0 (0.707106781186547 + 0.707106781186547j)]
244
+
245
+ A square root of a rotation matrix, giving the corresponding
246
+ half-angle rotation matrix::
247
+
248
+ >>> t1 = 0.75
249
+ >>> t2 = t1 * 0.5
250
+ >>> A1 = matrix([[cos(t1), -sin(t1)], [sin(t1), cos(t1)]])
251
+ >>> A2 = matrix([[cos(t2), -sin(t2)], [sin(t2), cos(t2)]])
252
+ >>> sqrtm(A1)
253
+ [0.930507621912314 -0.366272529086048]
254
+ [0.366272529086048 0.930507621912314]
255
+ >>> A2
256
+ [0.930507621912314 -0.366272529086048]
257
+ [0.366272529086048 0.930507621912314]
258
+
259
+ The identity `(A^2)^{1/2} = A` does not necessarily hold::
260
+
261
+ >>> A = matrix([[4,1,4],[7,8,9],[10,2,11]])
262
+ >>> sqrtm(A**2)
263
+ [ 4.0 1.0 4.0]
264
+ [ 7.0 8.0 9.0]
265
+ [10.0 2.0 11.0]
266
+ >>> sqrtm(A)**2
267
+ [ 4.0 1.0 4.0]
268
+ [ 7.0 8.0 9.0]
269
+ [10.0 2.0 11.0]
270
+ >>> A = matrix([[-4,1,4],[7,-8,9],[10,2,11]])
271
+ >>> sqrtm(A**2)
272
+ [ 7.43715112194995 -0.324127569985474 1.8481718827526]
273
+ [-0.251549715716942 9.32699765900402 2.48221180985147]
274
+ [ 4.11609388833616 0.775751877098258 13.017955697342]
275
+ >>> chop(sqrtm(A)**2)
276
+ [-4.0 1.0 4.0]
277
+ [ 7.0 -8.0 9.0]
278
+ [10.0 2.0 11.0]
279
+
280
+ For some matrices, a square root does not exist::
281
+
282
+ >>> sqrtm([[0,1], [0,0]])
283
+ Traceback (most recent call last):
284
+ ...
285
+ ZeroDivisionError: matrix is numerically singular
286
+
287
+ Two examples from the documentation for Matlab's ``sqrtm``::
288
+
289
+ >>> mp.dps = 15; mp.pretty = True
290
+ >>> sqrtm([[7,10],[15,22]])
291
+ [1.56669890360128 1.74077655955698]
292
+ [2.61116483933547 4.17786374293675]
293
+ >>>
294
+ >>> X = matrix(\
295
+ ... [[5,-4,1,0,0],
296
+ ... [-4,6,-4,1,0],
297
+ ... [1,-4,6,-4,1],
298
+ ... [0,1,-4,6,-4],
299
+ ... [0,0,1,-4,5]])
300
+ >>> Y = matrix(\
301
+ ... [[2,-1,-0,-0,-0],
302
+ ... [-1,2,-1,0,-0],
303
+ ... [0,-1,2,-1,0],
304
+ ... [-0,0,-1,2,-1],
305
+ ... [-0,-0,-0,-1,2]])
306
+ >>> mnorm(sqrtm(X) - Y)
307
+ 4.53155328326114e-19
308
+
309
+ """
310
+ A = ctx.matrix(A)
311
+ # Trivial
312
+ if A*0 == A:
313
+ return A
314
+ prec = ctx.prec
315
+ if _may_rotate:
316
+ d = ctx.det(A)
317
+ if abs(ctx.im(d)) < 16*ctx.eps and ctx.re(d) < 0:
318
+ return ctx._sqrtm_rot(A, _may_rotate-1)
319
+ try:
320
+ ctx.prec += 10
321
+ tol = ctx.eps * 128
322
+ Y = A
323
+ Z = I = A**0
324
+ k = 0
325
+ # Denman-Beavers iteration
326
+ while 1:
327
+ Yprev = Y
328
+ try:
329
+ Y, Z = 0.5*(Y+ctx.inverse(Z)), 0.5*(Z+ctx.inverse(Y))
330
+ except ZeroDivisionError:
331
+ if _may_rotate:
332
+ Y = ctx._sqrtm_rot(A, _may_rotate-1)
333
+ break
334
+ else:
335
+ raise
336
+ mag1 = ctx.mnorm(Y-Yprev, 'inf')
337
+ mag2 = ctx.mnorm(Y, 'inf')
338
+ if mag1 <= mag2*tol:
339
+ break
340
+ if _may_rotate and k > 6 and not mag1 < mag2 * 0.001:
341
+ return ctx._sqrtm_rot(A, _may_rotate-1)
342
+ k += 1
343
+ if k > ctx.prec:
344
+ raise ctx.NoConvergence
345
+ finally:
346
+ ctx.prec = prec
347
+ Y *= 1
348
+ return Y
349
+
350
+ def logm(ctx, A):
351
+ r"""
352
+ Computes a logarithm of the square matrix `A`, i.e. returns
353
+ a matrix `B = \log(A)` such that `\exp(B) = A`. The logarithm
354
+ of a matrix, if it exists, is not unique.
355
+
356
+ **Examples**
357
+
358
+ Logarithms of some simple matrices::
359
+
360
+ >>> from mpmath import *
361
+ >>> mp.dps = 15; mp.pretty = True
362
+ >>> X = eye(3)
363
+ >>> logm(X)
364
+ [0.0 0.0 0.0]
365
+ [0.0 0.0 0.0]
366
+ [0.0 0.0 0.0]
367
+ >>> logm(2*X)
368
+ [0.693147180559945 0.0 0.0]
369
+ [ 0.0 0.693147180559945 0.0]
370
+ [ 0.0 0.0 0.693147180559945]
371
+ >>> logm(expm(X))
372
+ [1.0 0.0 0.0]
373
+ [0.0 1.0 0.0]
374
+ [0.0 0.0 1.0]
375
+
376
+ A logarithm of a complex matrix::
377
+
378
+ >>> X = matrix([[2+j, 1, 3], [1-j, 1-2*j, 1], [-4, -5, j]])
379
+ >>> B = logm(X)
380
+ >>> nprint(B)
381
+ [ (0.808757 + 0.107759j) (2.20752 + 0.202762j) (1.07376 - 0.773874j)]
382
+ [ (0.905709 - 0.107795j) (0.0287395 - 0.824993j) (0.111619 + 0.514272j)]
383
+ [(-0.930151 + 0.399512j) (-2.06266 - 0.674397j) (0.791552 + 0.519839j)]
384
+ >>> chop(expm(B))
385
+ [(2.0 + 1.0j) 1.0 3.0]
386
+ [(1.0 - 1.0j) (1.0 - 2.0j) 1.0]
387
+ [ -4.0 -5.0 (0.0 + 1.0j)]
388
+
389
+ A matrix `X` close to the identity matrix, for which
390
+ `\log(\exp(X)) = \exp(\log(X)) = X` holds::
391
+
392
+ >>> X = eye(3) + hilbert(3)/4
393
+ >>> X
394
+ [ 1.25 0.125 0.0833333333333333]
395
+ [ 0.125 1.08333333333333 0.0625]
396
+ [0.0833333333333333 0.0625 1.05]
397
+ >>> logm(expm(X))
398
+ [ 1.25 0.125 0.0833333333333333]
399
+ [ 0.125 1.08333333333333 0.0625]
400
+ [0.0833333333333333 0.0625 1.05]
401
+ >>> expm(logm(X))
402
+ [ 1.25 0.125 0.0833333333333333]
403
+ [ 0.125 1.08333333333333 0.0625]
404
+ [0.0833333333333333 0.0625 1.05]
405
+
406
+ A logarithm of a rotation matrix, giving back the angle of
407
+ the rotation::
408
+
409
+ >>> t = 3.7
410
+ >>> A = matrix([[cos(t),sin(t)],[-sin(t),cos(t)]])
411
+ >>> chop(logm(A))
412
+ [ 0.0 -2.58318530717959]
413
+ [2.58318530717959 0.0]
414
+ >>> (2*pi-t)
415
+ 2.58318530717959
416
+
417
+ For some matrices, a logarithm does not exist::
418
+
419
+ >>> logm([[1,0], [0,0]])
420
+ Traceback (most recent call last):
421
+ ...
422
+ ZeroDivisionError: matrix is numerically singular
423
+
424
+ Logarithm of a matrix with large entries::
425
+
426
+ >>> logm(hilbert(3) * 10**20).apply(re)
427
+ [ 45.5597513593433 1.27721006042799 0.317662687717978]
428
+ [ 1.27721006042799 42.5222778973542 2.24003708791604]
429
+ [0.317662687717978 2.24003708791604 42.395212822267]
430
+
431
+ """
432
+ A = ctx.matrix(A)
433
+ prec = ctx.prec
434
+ try:
435
+ ctx.prec += 10
436
+ tol = ctx.eps * 128
437
+ I = A**0
438
+ B = A
439
+ n = 0
440
+ while 1:
441
+ B = ctx.sqrtm(B)
442
+ n += 1
443
+ if ctx.mnorm(B-I, 'inf') < 0.125:
444
+ break
445
+ T = X = B-I
446
+ L = X*0
447
+ k = 1
448
+ while 1:
449
+ if k & 1:
450
+ L += T / k
451
+ else:
452
+ L -= T / k
453
+ T *= X
454
+ if ctx.mnorm(T, 'inf') < tol:
455
+ break
456
+ k += 1
457
+ if k > ctx.prec:
458
+ raise ctx.NoConvergence
459
+ finally:
460
+ ctx.prec = prec
461
+ L *= 2**n
462
+ return L
463
+
464
+ def powm(ctx, A, r):
465
+ r"""
466
+ Computes `A^r = \exp(A \log r)` for a matrix `A` and complex
467
+ number `r`.
468
+
469
+ **Examples**
470
+
471
+ Powers and inverse powers of a matrix::
472
+
473
+ >>> from mpmath import *
474
+ >>> mp.dps = 15; mp.pretty = True
475
+ >>> A = matrix([[4,1,4],[7,8,9],[10,2,11]])
476
+ >>> powm(A, 2)
477
+ [ 63.0 20.0 69.0]
478
+ [174.0 89.0 199.0]
479
+ [164.0 48.0 179.0]
480
+ >>> chop(powm(powm(A, 4), 1/4.))
481
+ [ 4.0 1.0 4.0]
482
+ [ 7.0 8.0 9.0]
483
+ [10.0 2.0 11.0]
484
+ >>> powm(extraprec(20)(powm)(A, -4), -1/4.)
485
+ [ 4.0 1.0 4.0]
486
+ [ 7.0 8.0 9.0]
487
+ [10.0 2.0 11.0]
488
+ >>> chop(powm(powm(A, 1+0.5j), 1/(1+0.5j)))
489
+ [ 4.0 1.0 4.0]
490
+ [ 7.0 8.0 9.0]
491
+ [10.0 2.0 11.0]
492
+ >>> powm(extraprec(5)(powm)(A, -1.5), -1/(1.5))
493
+ [ 4.0 1.0 4.0]
494
+ [ 7.0 8.0 9.0]
495
+ [10.0 2.0 11.0]
496
+
497
+ A Fibonacci-generating matrix::
498
+
499
+ >>> powm([[1,1],[1,0]], 10)
500
+ [89.0 55.0]
501
+ [55.0 34.0]
502
+ >>> fib(10)
503
+ 55.0
504
+ >>> powm([[1,1],[1,0]], 6.5)
505
+ [(16.5166626964253 - 0.0121089837381789j) (10.2078589271083 + 0.0195927472575932j)]
506
+ [(10.2078589271083 + 0.0195927472575932j) (6.30880376931698 - 0.0317017309957721j)]
507
+ >>> (phi**6.5 - (1-phi)**6.5)/sqrt(5)
508
+ (10.2078589271083 - 0.0195927472575932j)
509
+ >>> powm([[1,1],[1,0]], 6.2)
510
+ [ (14.3076953002666 - 0.008222855781077j) (8.81733464837593 + 0.0133048601383712j)]
511
+ [(8.81733464837593 + 0.0133048601383712j) (5.49036065189071 - 0.0215277159194482j)]
512
+ >>> (phi**6.2 - (1-phi)**6.2)/sqrt(5)
513
+ (8.81733464837593 - 0.0133048601383712j)
514
+
515
+ """
516
+ A = ctx.matrix(A)
517
+ r = ctx.convert(r)
518
+ prec = ctx.prec
519
+ try:
520
+ ctx.prec += 10
521
+ if ctx.isint(r):
522
+ v = A ** int(r)
523
+ elif ctx.isint(r*2):
524
+ y = int(r*2)
525
+ v = ctx.sqrtm(A) ** y
526
+ else:
527
+ v = ctx.expm(r*ctx.logm(A))
528
+ finally:
529
+ ctx.prec = prec
530
+ v *= 1
531
+ return v
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/eigen.py ADDED
@@ -0,0 +1,877 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ ##################################################################################################
5
+ # module for the eigenvalue problem
6
+ # Copyright 2013 Timo Hartmann (thartmann15 at gmail.com)
7
+ #
8
+ # todo:
9
+ # - implement balancing
10
+ # - agressive early deflation
11
+ #
12
+ ##################################################################################################
13
+
14
+ """
15
+ The eigenvalue problem
16
+ ----------------------
17
+
18
+ This file contains routines for the eigenvalue problem.
19
+
20
+ high level routines:
21
+
22
+ hessenberg : reduction of a real or complex square matrix to upper Hessenberg form
23
+ schur : reduction of a real or complex square matrix to upper Schur form
24
+ eig : eigenvalues and eigenvectors of a real or complex square matrix
25
+
26
+ low level routines:
27
+
28
+ hessenberg_reduce_0 : reduction of a real or complex square matrix to upper Hessenberg form
29
+ hessenberg_reduce_1 : auxiliary routine to hessenberg_reduce_0
30
+ qr_step : a single implicitly shifted QR step for an upper Hessenberg matrix
31
+ hessenberg_qr : Schur decomposition of an upper Hessenberg matrix
32
+ eig_tr_r : right eigenvectors of an upper triangular matrix
33
+ eig_tr_l : left eigenvectors of an upper triangular matrix
34
+ """
35
+
36
+ from ..libmp.backend import xrange
37
+
38
+ class Eigen(object):
39
+ pass
40
+
41
+ def defun(f):
42
+ setattr(Eigen, f.__name__, f)
43
+ return f
44
+
45
+ def hessenberg_reduce_0(ctx, A, T):
46
+ """
47
+ This routine computes the (upper) Hessenberg decomposition of a square matrix A.
48
+ Given A, an unitary matrix Q is calculated such that
49
+
50
+ Q' A Q = H and Q' Q = Q Q' = 1
51
+
52
+ where H is an upper Hessenberg matrix, meaning that it only contains zeros
53
+ below the first subdiagonal. Here ' denotes the hermitian transpose (i.e.
54
+ transposition and conjugation).
55
+
56
+ parameters:
57
+ A (input/output) On input, A contains the square matrix A of
58
+ dimension (n,n). On output, A contains a compressed representation
59
+ of Q and H.
60
+ T (output) An array of length n containing the first elements of
61
+ the Householder reflectors.
62
+ """
63
+
64
+ # internally we work with householder reflections from the right.
65
+ # let u be a row vector (i.e. u[i]=A[i,:i]). then
66
+ # Q is build up by reflectors of the type (1-v'v) where v is a suitable
67
+ # modification of u. these reflectors are applyed to A from the right.
68
+ # because we work with reflectors from the right we have to start with
69
+ # the bottom row of A and work then upwards (this corresponds to
70
+ # some kind of RQ decomposition).
71
+ # the first part of the vectors v (i.e. A[i,:(i-1)]) are stored as row vectors
72
+ # in the lower left part of A (excluding the diagonal and subdiagonal).
73
+ # the last entry of v is stored in T.
74
+ # the upper right part of A (including diagonal and subdiagonal) becomes H.
75
+
76
+
77
+ n = A.rows
78
+ if n <= 2: return
79
+
80
+ for i in xrange(n-1, 1, -1):
81
+
82
+ # scale the vector
83
+
84
+ scale = 0
85
+ for k in xrange(0, i):
86
+ scale += abs(ctx.re(A[i,k])) + abs(ctx.im(A[i,k]))
87
+
88
+ scale_inv = 0
89
+ if scale != 0:
90
+ scale_inv = 1 / scale
91
+
92
+ if scale == 0 or ctx.isinf(scale_inv):
93
+ # sadly there are floating point numbers not equal to zero whose reciprocal is infinity
94
+ T[i] = 0
95
+ A[i,i-1] = 0
96
+ continue
97
+
98
+ # calculate parameters for housholder transformation
99
+
100
+ H = 0
101
+ for k in xrange(0, i):
102
+ A[i,k] *= scale_inv
103
+ rr = ctx.re(A[i,k])
104
+ ii = ctx.im(A[i,k])
105
+ H += rr * rr + ii * ii
106
+
107
+ F = A[i,i-1]
108
+ f = abs(F)
109
+ G = ctx.sqrt(H)
110
+ A[i,i-1] = - G * scale
111
+
112
+ if f == 0:
113
+ T[i] = G
114
+ else:
115
+ ff = F / f
116
+ T[i] = F + G * ff
117
+ A[i,i-1] *= ff
118
+
119
+ H += G * f
120
+ H = 1 / ctx.sqrt(H)
121
+
122
+ T[i] *= H
123
+ for k in xrange(0, i - 1):
124
+ A[i,k] *= H
125
+
126
+ for j in xrange(0, i):
127
+ # apply housholder transformation (from right)
128
+
129
+ G = ctx.conj(T[i]) * A[j,i-1]
130
+ for k in xrange(0, i-1):
131
+ G += ctx.conj(A[i,k]) * A[j,k]
132
+
133
+ A[j,i-1] -= G * T[i]
134
+ for k in xrange(0, i-1):
135
+ A[j,k] -= G * A[i,k]
136
+
137
+ for j in xrange(0, n):
138
+ # apply housholder transformation (from left)
139
+
140
+ G = T[i] * A[i-1,j]
141
+ for k in xrange(0, i-1):
142
+ G += A[i,k] * A[k,j]
143
+
144
+ A[i-1,j] -= G * ctx.conj(T[i])
145
+ for k in xrange(0, i-1):
146
+ A[k,j] -= G * ctx.conj(A[i,k])
147
+
148
+
149
+
150
+ def hessenberg_reduce_1(ctx, A, T):
151
+ """
152
+ This routine forms the unitary matrix Q described in hessenberg_reduce_0.
153
+
154
+ parameters:
155
+ A (input/output) On input, A is the same matrix as delivered by
156
+ hessenberg_reduce_0. On output, A is set to Q.
157
+
158
+ T (input) On input, T is the same array as delivered by hessenberg_reduce_0.
159
+ """
160
+
161
+ n = A.rows
162
+
163
+ if n == 1:
164
+ A[0,0] = 1
165
+ return
166
+
167
+ A[0,0] = A[1,1] = 1
168
+ A[0,1] = A[1,0] = 0
169
+
170
+ for i in xrange(2, n):
171
+ if T[i] != 0:
172
+
173
+ for j in xrange(0, i):
174
+ G = T[i] * A[i-1,j]
175
+ for k in xrange(0, i-1):
176
+ G += A[i,k] * A[k,j]
177
+
178
+ A[i-1,j] -= G * ctx.conj(T[i])
179
+ for k in xrange(0, i-1):
180
+ A[k,j] -= G * ctx.conj(A[i,k])
181
+
182
+ A[i,i] = 1
183
+ for j in xrange(0, i):
184
+ A[j,i] = A[i,j] = 0
185
+
186
+
187
+
188
+ @defun
189
+ def hessenberg(ctx, A, overwrite_a = False):
190
+ """
191
+ This routine computes the Hessenberg decomposition of a square matrix A.
192
+ Given A, an unitary matrix Q is determined such that
193
+
194
+ Q' A Q = H and Q' Q = Q Q' = 1
195
+
196
+ where H is an upper right Hessenberg matrix. Here ' denotes the hermitian
197
+ transpose (i.e. transposition and conjugation).
198
+
199
+ input:
200
+ A : a real or complex square matrix
201
+ overwrite_a : if true, allows modification of A which may improve
202
+ performance. if false, A is not modified.
203
+
204
+ output:
205
+ Q : an unitary matrix
206
+ H : an upper right Hessenberg matrix
207
+
208
+ example:
209
+ >>> from mpmath import mp
210
+ >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])
211
+ >>> Q, H = mp.hessenberg(A)
212
+ >>> mp.nprint(H, 3) # doctest:+SKIP
213
+ [ 3.15 2.23 4.44]
214
+ [-0.769 4.85 3.05]
215
+ [ 0.0 3.61 7.0]
216
+ >>> print(mp.chop(A - Q * H * Q.transpose_conj()))
217
+ [0.0 0.0 0.0]
218
+ [0.0 0.0 0.0]
219
+ [0.0 0.0 0.0]
220
+
221
+ return value: (Q, H)
222
+ """
223
+
224
+ n = A.rows
225
+
226
+ if n == 1:
227
+ return (ctx.matrix([[1]]), A)
228
+
229
+ if not overwrite_a:
230
+ A = A.copy()
231
+
232
+ T = ctx.matrix(n, 1)
233
+
234
+ hessenberg_reduce_0(ctx, A, T)
235
+ Q = A.copy()
236
+ hessenberg_reduce_1(ctx, Q, T)
237
+
238
+ for x in xrange(n):
239
+ for y in xrange(x+2, n):
240
+ A[y,x] = 0
241
+
242
+ return Q, A
243
+
244
+
245
+ ###########################################################################
246
+
247
+
248
+ def qr_step(ctx, n0, n1, A, Q, shift):
249
+ """
250
+ This subroutine executes a single implicitly shifted QR step applied to an
251
+ upper Hessenberg matrix A. Given A and shift as input, first an QR
252
+ decomposition is calculated:
253
+
254
+ Q R = A - shift * 1 .
255
+
256
+ The output is then following matrix:
257
+
258
+ R Q + shift * 1
259
+
260
+ parameters:
261
+ n0, n1 (input) Two integers which specify the submatrix A[n0:n1,n0:n1]
262
+ on which this subroutine operators. The subdiagonal elements
263
+ to the left and below this submatrix must be deflated (i.e. zero).
264
+ following restriction is imposed: n1>=n0+2
265
+ A (input/output) On input, A is an upper Hessenberg matrix.
266
+ On output, A is replaced by "R Q + shift * 1"
267
+ Q (input/output) The parameter Q is multiplied by the unitary matrix
268
+ Q arising from the QR decomposition. Q can also be false, in which
269
+ case the unitary matrix Q is not computated.
270
+ shift (input) a complex number specifying the shift. idealy close to an
271
+ eigenvalue of the bottemmost part of the submatrix A[n0:n1,n0:n1].
272
+
273
+ references:
274
+ Stoer, Bulirsch - Introduction to Numerical Analysis.
275
+ Kresser : Numerical Methods for General and Structured Eigenvalue Problems
276
+ """
277
+
278
+ # implicitly shifted and bulge chasing is explained at p.398/399 in "Stoer, Bulirsch - Introduction to Numerical Analysis"
279
+ # for bulge chasing see also "Watkins - The Matrix Eigenvalue Problem" sec.4.5,p.173
280
+
281
+ # the Givens rotation we used is determined as follows: let c,s be two complex
282
+ # numbers. then we have following relation:
283
+ #
284
+ # v = sqrt(|c|^2 + |s|^2)
285
+ #
286
+ # 1/v [ c~ s~] [c] = [v]
287
+ # [-s c ] [s] [0]
288
+ #
289
+ # the matrix on the left is our Givens rotation.
290
+
291
+ n = A.rows
292
+
293
+ # first step
294
+
295
+ # calculate givens rotation
296
+ c = A[n0 ,n0] - shift
297
+ s = A[n0+1,n0]
298
+
299
+ v = ctx.hypot(ctx.hypot(ctx.re(c), ctx.im(c)), ctx.hypot(ctx.re(s), ctx.im(s)))
300
+
301
+ if v == 0:
302
+ v = 1
303
+ c = 1
304
+ s = 0
305
+ else:
306
+ c /= v
307
+ s /= v
308
+
309
+ cc = ctx.conj(c)
310
+ cs = ctx.conj(s)
311
+
312
+ for k in xrange(n0, n):
313
+ # apply givens rotation from the left
314
+ x = A[n0 ,k]
315
+ y = A[n0+1,k]
316
+ A[n0 ,k] = cc * x + cs * y
317
+ A[n0+1,k] = c * y - s * x
318
+
319
+ for k in xrange(min(n1, n0+3)):
320
+ # apply givens rotation from the right
321
+ x = A[k,n0 ]
322
+ y = A[k,n0+1]
323
+ A[k,n0 ] = c * x + s * y
324
+ A[k,n0+1] = cc * y - cs * x
325
+
326
+ if not isinstance(Q, bool):
327
+ for k in xrange(n):
328
+ # eigenvectors
329
+ x = Q[k,n0 ]
330
+ y = Q[k,n0+1]
331
+ Q[k,n0 ] = c * x + s * y
332
+ Q[k,n0+1] = cc * y - cs * x
333
+
334
+ # chase the bulge
335
+
336
+ for j in xrange(n0, n1 - 2):
337
+ # calculate givens rotation
338
+
339
+ c = A[j+1,j]
340
+ s = A[j+2,j]
341
+
342
+ v = ctx.hypot(ctx.hypot(ctx.re(c), ctx.im(c)), ctx.hypot(ctx.re(s), ctx.im(s)))
343
+
344
+ if v == 0:
345
+ A[j+1,j] = 0
346
+ v = 1
347
+ c = 1
348
+ s = 0
349
+ else:
350
+ A[j+1,j] = v
351
+ c /= v
352
+ s /= v
353
+
354
+ A[j+2,j] = 0
355
+
356
+ cc = ctx.conj(c)
357
+ cs = ctx.conj(s)
358
+
359
+ for k in xrange(j+1, n):
360
+ # apply givens rotation from the left
361
+ x = A[j+1,k]
362
+ y = A[j+2,k]
363
+ A[j+1,k] = cc * x + cs * y
364
+ A[j+2,k] = c * y - s * x
365
+
366
+ for k in xrange(0, min(n1, j+4)):
367
+ # apply givens rotation from the right
368
+ x = A[k,j+1]
369
+ y = A[k,j+2]
370
+ A[k,j+1] = c * x + s * y
371
+ A[k,j+2] = cc * y - cs * x
372
+
373
+ if not isinstance(Q, bool):
374
+ for k in xrange(0, n):
375
+ # eigenvectors
376
+ x = Q[k,j+1]
377
+ y = Q[k,j+2]
378
+ Q[k,j+1] = c * x + s * y
379
+ Q[k,j+2] = cc * y - cs * x
380
+
381
+
382
+
383
+ def hessenberg_qr(ctx, A, Q):
384
+ """
385
+ This routine computes the Schur decomposition of an upper Hessenberg matrix A.
386
+ Given A, an unitary matrix Q is determined such that
387
+
388
+ Q' A Q = R and Q' Q = Q Q' = 1
389
+
390
+ where R is an upper right triangular matrix. Here ' denotes the hermitian
391
+ transpose (i.e. transposition and conjugation).
392
+
393
+ parameters:
394
+ A (input/output) On input, A contains an upper Hessenberg matrix.
395
+ On output, A is replace by the upper right triangluar matrix R.
396
+
397
+ Q (input/output) The parameter Q is multiplied by the unitary
398
+ matrix Q arising from the Schur decomposition. Q can also be
399
+ false, in which case the unitary matrix Q is not computated.
400
+ """
401
+
402
+ n = A.rows
403
+
404
+ norm = 0
405
+ for x in xrange(n):
406
+ for y in xrange(min(x+2, n)):
407
+ norm += ctx.re(A[y,x]) ** 2 + ctx.im(A[y,x]) ** 2
408
+ norm = ctx.sqrt(norm) / n
409
+
410
+ if norm == 0:
411
+ return
412
+
413
+ n0 = 0
414
+ n1 = n
415
+
416
+ eps = ctx.eps / (100 * n)
417
+ maxits = ctx.dps * 4
418
+
419
+ its = totalits = 0
420
+
421
+ while 1:
422
+ # kressner p.32 algo 3
423
+ # the active submatrix is A[n0:n1,n0:n1]
424
+
425
+ k = n0
426
+
427
+ while k + 1 < n1:
428
+ s = abs(ctx.re(A[k,k])) + abs(ctx.im(A[k,k])) + abs(ctx.re(A[k+1,k+1])) + abs(ctx.im(A[k+1,k+1]))
429
+ if s < eps * norm:
430
+ s = norm
431
+ if abs(A[k+1,k]) < eps * s:
432
+ break
433
+ k += 1
434
+
435
+ if k + 1 < n1:
436
+ # deflation found at position (k+1, k)
437
+
438
+ A[k+1,k] = 0
439
+ n0 = k + 1
440
+
441
+ its = 0
442
+
443
+ if n0 + 1 >= n1:
444
+ # block of size at most two has converged
445
+ n0 = 0
446
+ n1 = k + 1
447
+ if n1 < 2:
448
+ # QR algorithm has converged
449
+ return
450
+ else:
451
+ if (its % 30) == 10:
452
+ # exceptional shift
453
+ shift = A[n1-1,n1-2]
454
+ elif (its % 30) == 20:
455
+ # exceptional shift
456
+ shift = abs(A[n1-1,n1-2])
457
+ elif (its % 30) == 29:
458
+ # exceptional shift
459
+ shift = norm
460
+ else:
461
+ # A = [ a b ] det(x-A)=x*x-x*tr(A)+det(A)
462
+ # [ c d ]
463
+ #
464
+ # eigenvalues bad: (tr(A)+sqrt((tr(A))**2-4*det(A)))/2
465
+ # bad because of cancellation if |c| is small and |a-d| is small, too.
466
+ #
467
+ # eigenvalues good: (a+d+sqrt((a-d)**2+4*b*c))/2
468
+
469
+ t = A[n1-2,n1-2] + A[n1-1,n1-1]
470
+ s = (A[n1-1,n1-1] - A[n1-2,n1-2]) ** 2 + 4 * A[n1-1,n1-2] * A[n1-2,n1-1]
471
+ if ctx.re(s) > 0:
472
+ s = ctx.sqrt(s)
473
+ else:
474
+ s = ctx.sqrt(-s) * 1j
475
+ a = (t + s) / 2
476
+ b = (t - s) / 2
477
+ if abs(A[n1-1,n1-1] - a) > abs(A[n1-1,n1-1] - b):
478
+ shift = b
479
+ else:
480
+ shift = a
481
+
482
+ its += 1
483
+ totalits += 1
484
+
485
+ qr_step(ctx, n0, n1, A, Q, shift)
486
+
487
+ if its > maxits:
488
+ raise RuntimeError("qr: failed to converge after %d steps" % its)
489
+
490
+
491
+ @defun
492
+ def schur(ctx, A, overwrite_a = False):
493
+ """
494
+ This routine computes the Schur decomposition of a square matrix A.
495
+ Given A, an unitary matrix Q is determined such that
496
+
497
+ Q' A Q = R and Q' Q = Q Q' = 1
498
+
499
+ where R is an upper right triangular matrix. Here ' denotes the
500
+ hermitian transpose (i.e. transposition and conjugation).
501
+
502
+ input:
503
+ A : a real or complex square matrix
504
+ overwrite_a : if true, allows modification of A which may improve
505
+ performance. if false, A is not modified.
506
+
507
+ output:
508
+ Q : an unitary matrix
509
+ R : an upper right triangular matrix
510
+
511
+ return value: (Q, R)
512
+
513
+ example:
514
+ >>> from mpmath import mp
515
+ >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])
516
+ >>> Q, R = mp.schur(A)
517
+ >>> mp.nprint(R, 3) # doctest:+SKIP
518
+ [2.0 0.417 -2.53]
519
+ [0.0 4.0 -4.74]
520
+ [0.0 0.0 9.0]
521
+ >>> print(mp.chop(A - Q * R * Q.transpose_conj()))
522
+ [0.0 0.0 0.0]
523
+ [0.0 0.0 0.0]
524
+ [0.0 0.0 0.0]
525
+
526
+ warning: The Schur decomposition is not unique.
527
+ """
528
+
529
+ n = A.rows
530
+
531
+ if n == 1:
532
+ return (ctx.matrix([[1]]), A)
533
+
534
+ if not overwrite_a:
535
+ A = A.copy()
536
+
537
+ T = ctx.matrix(n, 1)
538
+
539
+ hessenberg_reduce_0(ctx, A, T)
540
+ Q = A.copy()
541
+ hessenberg_reduce_1(ctx, Q, T)
542
+
543
+ for x in xrange(n):
544
+ for y in xrange(x + 2, n):
545
+ A[y,x] = 0
546
+
547
+ hessenberg_qr(ctx, A, Q)
548
+
549
+ return Q, A
550
+
551
+
552
+ def eig_tr_r(ctx, A):
553
+ """
554
+ This routine calculates the right eigenvectors of an upper right triangular matrix.
555
+
556
+ input:
557
+ A an upper right triangular matrix
558
+
559
+ output:
560
+ ER a matrix whose columns form the right eigenvectors of A
561
+
562
+ return value: ER
563
+ """
564
+
565
+ # this subroutine is inspired by the lapack routines ctrevc.f,clatrs.f
566
+
567
+ n = A.rows
568
+
569
+ ER = ctx.eye(n)
570
+
571
+ eps = ctx.eps
572
+
573
+ unfl = ctx.ldexp(ctx.one, -ctx.prec * 30)
574
+ # since mpmath effectively has no limits on the exponent, we simply scale doubles up
575
+ # original double has prec*20
576
+
577
+ smlnum = unfl * (n / eps)
578
+ simin = 1 / ctx.sqrt(eps)
579
+
580
+ rmax = 1
581
+
582
+ for i in xrange(1, n):
583
+ s = A[i,i]
584
+
585
+ smin = max(eps * abs(s), smlnum)
586
+
587
+ for j in xrange(i - 1, -1, -1):
588
+
589
+ r = 0
590
+ for k in xrange(j + 1, i + 1):
591
+ r += A[j,k] * ER[k,i]
592
+
593
+ t = A[j,j] - s
594
+ if abs(t) < smin:
595
+ t = smin
596
+
597
+ r = -r / t
598
+ ER[j,i] = r
599
+
600
+ rmax = max(rmax, abs(r))
601
+ if rmax > simin:
602
+ for k in xrange(j, i+1):
603
+ ER[k,i] /= rmax
604
+ rmax = 1
605
+
606
+ if rmax != 1:
607
+ for k in xrange(0, i + 1):
608
+ ER[k,i] /= rmax
609
+
610
+ return ER
611
+
612
+ def eig_tr_l(ctx, A):
613
+ """
614
+ This routine calculates the left eigenvectors of an upper right triangular matrix.
615
+
616
+ input:
617
+ A an upper right triangular matrix
618
+
619
+ output:
620
+ EL a matrix whose rows form the left eigenvectors of A
621
+
622
+ return value: EL
623
+ """
624
+
625
+ n = A.rows
626
+
627
+ EL = ctx.eye(n)
628
+
629
+ eps = ctx.eps
630
+
631
+ unfl = ctx.ldexp(ctx.one, -ctx.prec * 30)
632
+ # since mpmath effectively has no limits on the exponent, we simply scale doubles up
633
+ # original double has prec*20
634
+
635
+ smlnum = unfl * (n / eps)
636
+ simin = 1 / ctx.sqrt(eps)
637
+
638
+ rmax = 1
639
+
640
+ for i in xrange(0, n - 1):
641
+ s = A[i,i]
642
+
643
+ smin = max(eps * abs(s), smlnum)
644
+
645
+ for j in xrange(i + 1, n):
646
+
647
+ r = 0
648
+ for k in xrange(i, j):
649
+ r += EL[i,k] * A[k,j]
650
+
651
+ t = A[j,j] - s
652
+ if abs(t) < smin:
653
+ t = smin
654
+
655
+ r = -r / t
656
+ EL[i,j] = r
657
+
658
+ rmax = max(rmax, abs(r))
659
+ if rmax > simin:
660
+ for k in xrange(i, j + 1):
661
+ EL[i,k] /= rmax
662
+ rmax = 1
663
+
664
+ if rmax != 1:
665
+ for k in xrange(i, n):
666
+ EL[i,k] /= rmax
667
+
668
+ return EL
669
+
670
+ @defun
671
+ def eig(ctx, A, left = False, right = True, overwrite_a = False):
672
+ """
673
+ This routine computes the eigenvalues and optionally the left and right
674
+ eigenvectors of a square matrix A. Given A, a vector E and matrices ER
675
+ and EL are calculated such that
676
+
677
+ A ER[:,i] = E[i] ER[:,i]
678
+ EL[i,:] A = EL[i,:] E[i]
679
+
680
+ E contains the eigenvalues of A. The columns of ER contain the right eigenvectors
681
+ of A whereas the rows of EL contain the left eigenvectors.
682
+
683
+
684
+ input:
685
+ A : a real or complex square matrix of shape (n, n)
686
+ left : if true, the left eigenvectors are calculated.
687
+ right : if true, the right eigenvectors are calculated.
688
+ overwrite_a : if true, allows modification of A which may improve
689
+ performance. if false, A is not modified.
690
+
691
+ output:
692
+ E : a list of length n containing the eigenvalues of A.
693
+ ER : a matrix whose columns contain the right eigenvectors of A.
694
+ EL : a matrix whose rows contain the left eigenvectors of A.
695
+
696
+ return values:
697
+ E if left and right are both false.
698
+ (E, ER) if right is true and left is false.
699
+ (E, EL) if left is true and right is false.
700
+ (E, EL, ER) if left and right are true.
701
+
702
+
703
+ examples:
704
+ >>> from mpmath import mp
705
+ >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])
706
+ >>> E, ER = mp.eig(A)
707
+ >>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0]))
708
+ [0.0]
709
+ [0.0]
710
+ [0.0]
711
+
712
+ >>> E, EL, ER = mp.eig(A,left = True, right = True)
713
+ >>> E, EL, ER = mp.eig_sort(E, EL, ER)
714
+ >>> mp.nprint(E)
715
+ [2.0, 4.0, 9.0]
716
+ >>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0]))
717
+ [0.0]
718
+ [0.0]
719
+ [0.0]
720
+ >>> print(mp.chop( EL[0,:] * A - EL[0,:] * E[0]))
721
+ [0.0 0.0 0.0]
722
+
723
+ warning:
724
+ - If there are multiple eigenvalues, the eigenvectors do not necessarily
725
+ span the whole vectorspace, i.e. ER and EL may have not full rank.
726
+ Furthermore in that case the eigenvectors are numerical ill-conditioned.
727
+ - In the general case the eigenvalues have no natural order.
728
+
729
+ see also:
730
+ - eigh (or eigsy, eighe) for the symmetric eigenvalue problem.
731
+ - eig_sort for sorting of eigenvalues and eigenvectors
732
+ """
733
+
734
+ n = A.rows
735
+
736
+ if n == 1:
737
+ if left and (not right):
738
+ return ([A[0]], ctx.matrix([[1]]))
739
+
740
+ if right and (not left):
741
+ return ([A[0]], ctx.matrix([[1]]))
742
+
743
+ return ([A[0]], ctx.matrix([[1]]), ctx.matrix([[1]]))
744
+
745
+ if not overwrite_a:
746
+ A = A.copy()
747
+
748
+ T = ctx.zeros(n, 1)
749
+
750
+ hessenberg_reduce_0(ctx, A, T)
751
+
752
+ if left or right:
753
+ Q = A.copy()
754
+ hessenberg_reduce_1(ctx, Q, T)
755
+ else:
756
+ Q = False
757
+
758
+ for x in xrange(n):
759
+ for y in xrange(x + 2, n):
760
+ A[y,x] = 0
761
+
762
+ hessenberg_qr(ctx, A, Q)
763
+
764
+ E = [0 for i in xrange(n)]
765
+ for i in xrange(n):
766
+ E[i] = A[i,i]
767
+
768
+ if not (left or right):
769
+ return E
770
+
771
+ if left:
772
+ EL = eig_tr_l(ctx, A)
773
+ EL = EL * Q.transpose_conj()
774
+
775
+ if right:
776
+ ER = eig_tr_r(ctx, A)
777
+ ER = Q * ER
778
+
779
+ if left and (not right):
780
+ return (E, EL)
781
+
782
+ if right and (not left):
783
+ return (E, ER)
784
+
785
+ return (E, EL, ER)
786
+
787
+ @defun
788
+ def eig_sort(ctx, E, EL = False, ER = False, f = "real"):
789
+ """
790
+ This routine sorts the eigenvalues and eigenvectors delivered by ``eig``.
791
+
792
+ parameters:
793
+ E : the eigenvalues as delivered by eig
794
+ EL : the left eigenvectors as delivered by eig, or false
795
+ ER : the right eigenvectors as delivered by eig, or false
796
+ f : either a string ("real" sort by increasing real part, "imag" sort by
797
+ increasing imag part, "abs" sort by absolute value) or a function
798
+ mapping complexs to the reals, i.e. ``f = lambda x: -mp.re(x) ``
799
+ would sort the eigenvalues by decreasing real part.
800
+
801
+ return values:
802
+ E if EL and ER are both false.
803
+ (E, ER) if ER is not false and left is false.
804
+ (E, EL) if EL is not false and right is false.
805
+ (E, EL, ER) if EL and ER are not false.
806
+
807
+ example:
808
+ >>> from mpmath import mp
809
+ >>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])
810
+ >>> E, EL, ER = mp.eig(A,left = True, right = True)
811
+ >>> E, EL, ER = mp.eig_sort(E, EL, ER)
812
+ >>> mp.nprint(E)
813
+ [2.0, 4.0, 9.0]
814
+ >>> E, EL, ER = mp.eig_sort(E, EL, ER,f = lambda x: -mp.re(x))
815
+ >>> mp.nprint(E)
816
+ [9.0, 4.0, 2.0]
817
+ >>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0]))
818
+ [0.0]
819
+ [0.0]
820
+ [0.0]
821
+ >>> print(mp.chop( EL[0,:] * A - EL[0,:] * E[0]))
822
+ [0.0 0.0 0.0]
823
+ """
824
+
825
+ if isinstance(f, str):
826
+ if f == "real":
827
+ f = ctx.re
828
+ elif f == "imag":
829
+ f = ctx.im
830
+ elif f == "abs":
831
+ f = abs
832
+ else:
833
+ raise RuntimeError("unknown function %s" % f)
834
+
835
+ n = len(E)
836
+
837
+ # Sort eigenvalues (bubble-sort)
838
+
839
+ for i in xrange(n):
840
+ imax = i
841
+ s = f(E[i]) # s is the current maximal element
842
+
843
+ for j in xrange(i + 1, n):
844
+ c = f(E[j])
845
+ if c < s:
846
+ s = c
847
+ imax = j
848
+
849
+ if imax != i:
850
+ # swap eigenvalues
851
+
852
+ z = E[i]
853
+ E[i] = E[imax]
854
+ E[imax] = z
855
+
856
+ if not isinstance(EL, bool):
857
+ for j in xrange(n):
858
+ z = EL[i,j]
859
+ EL[i,j] = EL[imax,j]
860
+ EL[imax,j] = z
861
+
862
+ if not isinstance(ER, bool):
863
+ for j in xrange(n):
864
+ z = ER[j,i]
865
+ ER[j,i] = ER[j,imax]
866
+ ER[j,imax] = z
867
+
868
+ if isinstance(EL, bool) and isinstance(ER, bool):
869
+ return E
870
+
871
+ if isinstance(EL, bool) and not(isinstance(ER, bool)):
872
+ return (E, ER)
873
+
874
+ if isinstance(ER, bool) and not(isinstance(EL, bool)):
875
+ return (E, EL)
876
+
877
+ return (E, EL, ER)
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/linalg.py ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Linear algebra
3
+ --------------
4
+
5
+ Linear equations
6
+ ................
7
+
8
+ Basic linear algebra is implemented; you can for example solve the linear
9
+ equation system::
10
+
11
+ x + 2*y = -10
12
+ 3*x + 4*y = 10
13
+
14
+ using ``lu_solve``::
15
+
16
+ >>> from mpmath import *
17
+ >>> mp.pretty = False
18
+ >>> A = matrix([[1, 2], [3, 4]])
19
+ >>> b = matrix([-10, 10])
20
+ >>> x = lu_solve(A, b)
21
+ >>> x
22
+ matrix(
23
+ [['30.0'],
24
+ ['-20.0']])
25
+
26
+ If you don't trust the result, use ``residual`` to calculate the residual ||A*x-b||::
27
+
28
+ >>> residual(A, x, b)
29
+ matrix(
30
+ [['3.46944695195361e-18'],
31
+ ['3.46944695195361e-18']])
32
+ >>> str(eps)
33
+ '2.22044604925031e-16'
34
+
35
+ As you can see, the solution is quite accurate. The error is caused by the
36
+ inaccuracy of the internal floating point arithmetic. Though, it's even smaller
37
+ than the current machine epsilon, which basically means you can trust the
38
+ result.
39
+
40
+ If you need more speed, use NumPy, or ``fp.lu_solve`` for a floating-point computation.
41
+
42
+ >>> fp.lu_solve(A, b) # doctest: +ELLIPSIS
43
+ matrix(...)
44
+
45
+ ``lu_solve`` accepts overdetermined systems. It is usually not possible to solve
46
+ such systems, so the residual is minimized instead. Internally this is done
47
+ using Cholesky decomposition to compute a least squares approximation. This means
48
+ that that ``lu_solve`` will square the errors. If you can't afford this, use
49
+ ``qr_solve`` instead. It is twice as slow but more accurate, and it calculates
50
+ the residual automatically.
51
+
52
+
53
+ Matrix factorization
54
+ ....................
55
+
56
+ The function ``lu`` computes an explicit LU factorization of a matrix::
57
+
58
+ >>> P, L, U = lu(matrix([[0,2,3],[4,5,6],[7,8,9]]))
59
+ >>> print(P)
60
+ [0.0 0.0 1.0]
61
+ [1.0 0.0 0.0]
62
+ [0.0 1.0 0.0]
63
+ >>> print(L)
64
+ [ 1.0 0.0 0.0]
65
+ [ 0.0 1.0 0.0]
66
+ [0.571428571428571 0.214285714285714 1.0]
67
+ >>> print(U)
68
+ [7.0 8.0 9.0]
69
+ [0.0 2.0 3.0]
70
+ [0.0 0.0 0.214285714285714]
71
+ >>> print(P.T*L*U)
72
+ [0.0 2.0 3.0]
73
+ [4.0 5.0 6.0]
74
+ [7.0 8.0 9.0]
75
+
76
+ Interval matrices
77
+ -----------------
78
+
79
+ Matrices may contain interval elements. This allows one to perform
80
+ basic linear algebra operations such as matrix multiplication
81
+ and equation solving with rigorous error bounds::
82
+
83
+ >>> a = iv.matrix([['0.1','0.3','1.0'],
84
+ ... ['7.1','5.5','4.8'],
85
+ ... ['3.2','4.4','5.6']])
86
+ >>>
87
+ >>> b = iv.matrix(['4','0.6','0.5'])
88
+ >>> c = iv.lu_solve(a, b)
89
+ >>> print(c)
90
+ [ [5.2582327113062568605927528666, 5.25823271130625686059275702219]]
91
+ [[-13.1550493962678375411635581388, -13.1550493962678375411635540152]]
92
+ [ [7.42069154774972557628979076189, 7.42069154774972557628979190734]]
93
+ >>> print(a*c)
94
+ [ [3.99999999999999999999999844904, 4.00000000000000000000000155096]]
95
+ [[0.599999999999999999999968898009, 0.600000000000000000000031763736]]
96
+ [[0.499999999999999999999979320485, 0.500000000000000000000020679515]]
97
+ """
98
+
99
+ # TODO:
100
+ # *implement high-level qr()
101
+ # *test unitvector
102
+ # *iterative solving
103
+
104
+ from copy import copy
105
+
106
+ from ..libmp.backend import xrange
107
+
108
+ class LinearAlgebraMethods(object):
109
+
110
+ def LU_decomp(ctx, A, overwrite=False, use_cache=True):
111
+ """
112
+ LU-factorization of a n*n matrix using the Gauss algorithm.
113
+ Returns L and U in one matrix and the pivot indices.
114
+
115
+ Use overwrite to specify whether A will be overwritten with L and U.
116
+ """
117
+ if not A.rows == A.cols:
118
+ raise ValueError('need n*n matrix')
119
+ # get from cache if possible
120
+ if use_cache and isinstance(A, ctx.matrix) and A._LU:
121
+ return A._LU
122
+ if not overwrite:
123
+ orig = A
124
+ A = A.copy()
125
+ tol = ctx.absmin(ctx.mnorm(A,1) * ctx.eps) # each pivot element has to be bigger
126
+ n = A.rows
127
+ p = [None]*(n - 1)
128
+ for j in xrange(n - 1):
129
+ # pivoting, choose max(abs(reciprocal row sum)*abs(pivot element))
130
+ biggest = 0
131
+ for k in xrange(j, n):
132
+ s = ctx.fsum([ctx.absmin(A[k,l]) for l in xrange(j, n)])
133
+ if ctx.absmin(s) <= tol:
134
+ raise ZeroDivisionError('matrix is numerically singular')
135
+ current = 1/s * ctx.absmin(A[k,j])
136
+ if current > biggest: # TODO: what if equal?
137
+ biggest = current
138
+ p[j] = k
139
+ # swap rows according to p
140
+ ctx.swap_row(A, j, p[j])
141
+ if ctx.absmin(A[j,j]) <= tol:
142
+ raise ZeroDivisionError('matrix is numerically singular')
143
+ # calculate elimination factors and add rows
144
+ for i in xrange(j + 1, n):
145
+ A[i,j] /= A[j,j]
146
+ for k in xrange(j + 1, n):
147
+ A[i,k] -= A[i,j]*A[j,k]
148
+ if ctx.absmin(A[n - 1,n - 1]) <= tol:
149
+ raise ZeroDivisionError('matrix is numerically singular')
150
+ # cache decomposition
151
+ if not overwrite and isinstance(orig, ctx.matrix):
152
+ orig._LU = (A, p)
153
+ return A, p
154
+
155
+ def L_solve(ctx, L, b, p=None):
156
+ """
157
+ Solve the lower part of a LU factorized matrix for y.
158
+ """
159
+ if L.rows != L.cols:
160
+ raise RuntimeError("need n*n matrix")
161
+ n = L.rows
162
+ if len(b) != n:
163
+ raise ValueError("Value should be equal to n")
164
+ b = copy(b)
165
+ if p: # swap b according to p
166
+ for k in xrange(0, len(p)):
167
+ ctx.swap_row(b, k, p[k])
168
+ # solve
169
+ for i in xrange(1, n):
170
+ for j in xrange(i):
171
+ b[i] -= L[i,j] * b[j]
172
+ return b
173
+
174
+ def U_solve(ctx, U, y):
175
+ """
176
+ Solve the upper part of a LU factorized matrix for x.
177
+ """
178
+ if U.rows != U.cols:
179
+ raise RuntimeError("need n*n matrix")
180
+ n = U.rows
181
+ if len(y) != n:
182
+ raise ValueError("Value should be equal to n")
183
+ x = copy(y)
184
+ for i in xrange(n - 1, -1, -1):
185
+ for j in xrange(i + 1, n):
186
+ x[i] -= U[i,j] * x[j]
187
+ x[i] /= U[i,i]
188
+ return x
189
+
190
+ def lu_solve(ctx, A, b, **kwargs):
191
+ """
192
+ Ax = b => x
193
+
194
+ Solve a determined or overdetermined linear equations system.
195
+ Fast LU decomposition is used, which is less accurate than QR decomposition
196
+ (especially for overdetermined systems), but it's twice as efficient.
197
+ Use qr_solve if you want more precision or have to solve a very ill-
198
+ conditioned system.
199
+
200
+ If you specify real=True, it does not check for overdeterminded complex
201
+ systems.
202
+ """
203
+ prec = ctx.prec
204
+ try:
205
+ ctx.prec += 10
206
+ # do not overwrite A nor b
207
+ A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()
208
+ if A.rows < A.cols:
209
+ raise ValueError('cannot solve underdetermined system')
210
+ if A.rows > A.cols:
211
+ # use least-squares method if overdetermined
212
+ # (this increases errors)
213
+ AH = A.H
214
+ A = AH * A
215
+ b = AH * b
216
+ if (kwargs.get('real', False) or
217
+ not sum(type(i) is ctx.mpc for i in A)):
218
+ # TODO: necessary to check also b?
219
+ x = ctx.cholesky_solve(A, b)
220
+ else:
221
+ x = ctx.lu_solve(A, b)
222
+ else:
223
+ # LU factorization
224
+ A, p = ctx.LU_decomp(A)
225
+ b = ctx.L_solve(A, b, p)
226
+ x = ctx.U_solve(A, b)
227
+ finally:
228
+ ctx.prec = prec
229
+ return x
230
+
231
+ def improve_solution(ctx, A, x, b, maxsteps=1):
232
+ """
233
+ Improve a solution to a linear equation system iteratively.
234
+
235
+ This re-uses the LU decomposition and is thus cheap.
236
+ Usually 3 up to 4 iterations are giving the maximal improvement.
237
+ """
238
+ if A.rows != A.cols:
239
+ raise RuntimeError("need n*n matrix") # TODO: really?
240
+ for _ in xrange(maxsteps):
241
+ r = ctx.residual(A, x, b)
242
+ if ctx.norm(r, 2) < 10*ctx.eps:
243
+ break
244
+ # this uses cached LU decomposition and is thus cheap
245
+ dx = ctx.lu_solve(A, -r)
246
+ x += dx
247
+ return x
248
+
249
+ def lu(ctx, A):
250
+ """
251
+ A -> P, L, U
252
+
253
+ LU factorisation of a square matrix A. L is the lower, U the upper part.
254
+ P is the permutation matrix indicating the row swaps.
255
+
256
+ P*A = L*U
257
+
258
+ If you need efficiency, use the low-level method LU_decomp instead, it's
259
+ much more memory efficient.
260
+ """
261
+ # get factorization
262
+ A, p = ctx.LU_decomp(A)
263
+ n = A.rows
264
+ L = ctx.matrix(n)
265
+ U = ctx.matrix(n)
266
+ for i in xrange(n):
267
+ for j in xrange(n):
268
+ if i > j:
269
+ L[i,j] = A[i,j]
270
+ elif i == j:
271
+ L[i,j] = 1
272
+ U[i,j] = A[i,j]
273
+ else:
274
+ U[i,j] = A[i,j]
275
+ # calculate permutation matrix
276
+ P = ctx.eye(n)
277
+ for k in xrange(len(p)):
278
+ ctx.swap_row(P, k, p[k])
279
+ return P, L, U
280
+
281
+ def unitvector(ctx, n, i):
282
+ """
283
+ Return the i-th n-dimensional unit vector.
284
+ """
285
+ assert 0 < i <= n, 'this unit vector does not exist'
286
+ return [ctx.zero]*(i-1) + [ctx.one] + [ctx.zero]*(n-i)
287
+
288
+ def inverse(ctx, A, **kwargs):
289
+ """
290
+ Calculate the inverse of a matrix.
291
+
292
+ If you want to solve an equation system Ax = b, it's recommended to use
293
+ solve(A, b) instead, it's about 3 times more efficient.
294
+ """
295
+ prec = ctx.prec
296
+ try:
297
+ ctx.prec += 10
298
+ # do not overwrite A
299
+ A = ctx.matrix(A, **kwargs).copy()
300
+ n = A.rows
301
+ # get LU factorisation
302
+ A, p = ctx.LU_decomp(A)
303
+ cols = []
304
+ # calculate unit vectors and solve corresponding system to get columns
305
+ for i in xrange(1, n + 1):
306
+ e = ctx.unitvector(n, i)
307
+ y = ctx.L_solve(A, e, p)
308
+ cols.append(ctx.U_solve(A, y))
309
+ # convert columns to matrix
310
+ inv = []
311
+ for i in xrange(n):
312
+ row = []
313
+ for j in xrange(n):
314
+ row.append(cols[j][i])
315
+ inv.append(row)
316
+ result = ctx.matrix(inv, **kwargs)
317
+ finally:
318
+ ctx.prec = prec
319
+ return result
320
+
321
+ def householder(ctx, A):
322
+ """
323
+ (A|b) -> H, p, x, res
324
+
325
+ (A|b) is the coefficient matrix with left hand side of an optionally
326
+ overdetermined linear equation system.
327
+ H and p contain all information about the transformation matrices.
328
+ x is the solution, res the residual.
329
+ """
330
+ if not isinstance(A, ctx.matrix):
331
+ raise TypeError("A should be a type of ctx.matrix")
332
+ m = A.rows
333
+ n = A.cols
334
+ if m < n - 1:
335
+ raise RuntimeError("Columns should not be less than rows")
336
+ # calculate Householder matrix
337
+ p = []
338
+ for j in xrange(0, n - 1):
339
+ s = ctx.fsum(abs(A[i,j])**2 for i in xrange(j, m))
340
+ if not abs(s) > ctx.eps:
341
+ raise ValueError('matrix is numerically singular')
342
+ p.append(-ctx.sign(ctx.re(A[j,j])) * ctx.sqrt(s))
343
+ kappa = ctx.one / (s - p[j] * A[j,j])
344
+ A[j,j] -= p[j]
345
+ for k in xrange(j+1, n):
346
+ y = ctx.fsum(ctx.conj(A[i,j]) * A[i,k] for i in xrange(j, m)) * kappa
347
+ for i in xrange(j, m):
348
+ A[i,k] -= A[i,j] * y
349
+ # solve Rx = c1
350
+ x = [A[i,n - 1] for i in xrange(n - 1)]
351
+ for i in xrange(n - 2, -1, -1):
352
+ x[i] -= ctx.fsum(A[i,j] * x[j] for j in xrange(i + 1, n - 1))
353
+ x[i] /= p[i]
354
+ # calculate residual
355
+ if not m == n - 1:
356
+ r = [A[m-1-i, n-1] for i in xrange(m - n + 1)]
357
+ else:
358
+ # determined system, residual should be 0
359
+ r = [0]*m # maybe a bad idea, changing r[i] will change all elements
360
+ return A, p, x, r
361
+
362
+ #def qr(ctx, A):
363
+ # """
364
+ # A -> Q, R
365
+ #
366
+ # QR factorisation of a square matrix A using Householder decomposition.
367
+ # Q is orthogonal, this leads to very few numerical errors.
368
+ #
369
+ # A = Q*R
370
+ # """
371
+ # H, p, x, res = householder(A)
372
+ # TODO: implement this
373
+
374
+ def residual(ctx, A, x, b, **kwargs):
375
+ """
376
+ Calculate the residual of a solution to a linear equation system.
377
+
378
+ r = A*x - b for A*x = b
379
+ """
380
+ oldprec = ctx.prec
381
+ try:
382
+ ctx.prec *= 2
383
+ A, x, b = ctx.matrix(A, **kwargs), ctx.matrix(x, **kwargs), ctx.matrix(b, **kwargs)
384
+ return A*x - b
385
+ finally:
386
+ ctx.prec = oldprec
387
+
388
+ def qr_solve(ctx, A, b, norm=None, **kwargs):
389
+ """
390
+ Ax = b => x, ||Ax - b||
391
+
392
+ Solve a determined or overdetermined linear equations system and
393
+ calculate the norm of the residual (error).
394
+ QR decomposition using Householder factorization is applied, which gives very
395
+ accurate results even for ill-conditioned matrices. qr_solve is twice as
396
+ efficient.
397
+ """
398
+ if norm is None:
399
+ norm = ctx.norm
400
+ prec = ctx.prec
401
+ try:
402
+ ctx.prec += 10
403
+ # do not overwrite A nor b
404
+ A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()
405
+ if A.rows < A.cols:
406
+ raise ValueError('cannot solve underdetermined system')
407
+ H, p, x, r = ctx.householder(ctx.extend(A, b))
408
+ res = ctx.norm(r)
409
+ # calculate residual "manually" for determined systems
410
+ if res == 0:
411
+ res = ctx.norm(ctx.residual(A, x, b))
412
+ return ctx.matrix(x, **kwargs), res
413
+ finally:
414
+ ctx.prec = prec
415
+
416
+ def cholesky(ctx, A, tol=None):
417
+ r"""
418
+ Cholesky decomposition of a symmetric positive-definite matrix `A`.
419
+ Returns a lower triangular matrix `L` such that `A = L \times L^T`.
420
+ More generally, for a complex Hermitian positive-definite matrix,
421
+ a Cholesky decomposition satisfying `A = L \times L^H` is returned.
422
+
423
+ The Cholesky decomposition can be used to solve linear equation
424
+ systems twice as efficiently as LU decomposition, or to
425
+ test whether `A` is positive-definite.
426
+
427
+ The optional parameter ``tol`` determines the tolerance for
428
+ verifying positive-definiteness.
429
+
430
+ **Examples**
431
+
432
+ Cholesky decomposition of a positive-definite symmetric matrix::
433
+
434
+ >>> from mpmath import *
435
+ >>> mp.dps = 25; mp.pretty = True
436
+ >>> A = eye(3) + hilbert(3)
437
+ >>> nprint(A)
438
+ [ 2.0 0.5 0.333333]
439
+ [ 0.5 1.33333 0.25]
440
+ [0.333333 0.25 1.2]
441
+ >>> L = cholesky(A)
442
+ >>> nprint(L)
443
+ [ 1.41421 0.0 0.0]
444
+ [0.353553 1.09924 0.0]
445
+ [0.235702 0.15162 1.05899]
446
+ >>> chop(A - L*L.T)
447
+ [0.0 0.0 0.0]
448
+ [0.0 0.0 0.0]
449
+ [0.0 0.0 0.0]
450
+
451
+ Cholesky decomposition of a Hermitian matrix::
452
+
453
+ >>> A = eye(3) + matrix([[0,0.25j,-0.5j],[-0.25j,0,0],[0.5j,0,0]])
454
+ >>> L = cholesky(A)
455
+ >>> nprint(L)
456
+ [ 1.0 0.0 0.0]
457
+ [(0.0 - 0.25j) (0.968246 + 0.0j) 0.0]
458
+ [ (0.0 + 0.5j) (0.129099 + 0.0j) (0.856349 + 0.0j)]
459
+ >>> chop(A - L*L.H)
460
+ [0.0 0.0 0.0]
461
+ [0.0 0.0 0.0]
462
+ [0.0 0.0 0.0]
463
+
464
+ Attempted Cholesky decomposition of a matrix that is not positive
465
+ definite::
466
+
467
+ >>> A = -eye(3) + hilbert(3)
468
+ >>> L = cholesky(A)
469
+ Traceback (most recent call last):
470
+ ...
471
+ ValueError: matrix is not positive-definite
472
+
473
+ **References**
474
+
475
+ 1. [Wikipedia]_ http://en.wikipedia.org/wiki/Cholesky_decomposition
476
+
477
+ """
478
+ if not isinstance(A, ctx.matrix):
479
+ raise RuntimeError("A should be a type of ctx.matrix")
480
+ if not A.rows == A.cols:
481
+ raise ValueError('need n*n matrix')
482
+ if tol is None:
483
+ tol = +ctx.eps
484
+ n = A.rows
485
+ L = ctx.matrix(n)
486
+ for j in xrange(n):
487
+ c = ctx.re(A[j,j])
488
+ if abs(c-A[j,j]) > tol:
489
+ raise ValueError('matrix is not Hermitian')
490
+ s = c - ctx.fsum((L[j,k] for k in xrange(j)),
491
+ absolute=True, squared=True)
492
+ if s < tol:
493
+ raise ValueError('matrix is not positive-definite')
494
+ L[j,j] = ctx.sqrt(s)
495
+ for i in xrange(j, n):
496
+ it1 = (L[i,k] for k in xrange(j))
497
+ it2 = (L[j,k] for k in xrange(j))
498
+ t = ctx.fdot(it1, it2, conjugate=True)
499
+ L[i,j] = (A[i,j] - t) / L[j,j]
500
+ return L
501
+
502
+ def cholesky_solve(ctx, A, b, **kwargs):
503
+ """
504
+ Ax = b => x
505
+
506
+ Solve a symmetric positive-definite linear equation system.
507
+ This is twice as efficient as lu_solve.
508
+
509
+ Typical use cases:
510
+ * A.T*A
511
+ * Hessian matrix
512
+ * differential equations
513
+ """
514
+ prec = ctx.prec
515
+ try:
516
+ ctx.prec += 10
517
+ # do not overwrite A nor b
518
+ A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()
519
+ if A.rows != A.cols:
520
+ raise ValueError('can only solve determined system')
521
+ # Cholesky factorization
522
+ L = ctx.cholesky(A)
523
+ # solve
524
+ n = L.rows
525
+ if len(b) != n:
526
+ raise ValueError("Value should be equal to n")
527
+ for i in xrange(n):
528
+ b[i] -= ctx.fsum(L[i,j] * b[j] for j in xrange(i))
529
+ b[i] /= L[i,i]
530
+ x = ctx.U_solve(L.T, b)
531
+ return x
532
+ finally:
533
+ ctx.prec = prec
534
+
535
+ def det(ctx, A):
536
+ """
537
+ Calculate the determinant of a matrix.
538
+ """
539
+ prec = ctx.prec
540
+ try:
541
+ # do not overwrite A
542
+ A = ctx.matrix(A).copy()
543
+ # use LU factorization to calculate determinant
544
+ try:
545
+ R, p = ctx.LU_decomp(A)
546
+ except ZeroDivisionError:
547
+ return 0
548
+ z = 1
549
+ for i, e in enumerate(p):
550
+ if i != e:
551
+ z *= -1
552
+ for i in xrange(A.rows):
553
+ z *= R[i,i]
554
+ return z
555
+ finally:
556
+ ctx.prec = prec
557
+
558
+ def cond(ctx, A, norm=None):
559
+ """
560
+ Calculate the condition number of a matrix using a specified matrix norm.
561
+
562
+ The condition number estimates the sensitivity of a matrix to errors.
563
+ Example: small input errors for ill-conditioned coefficient matrices
564
+ alter the solution of the system dramatically.
565
+
566
+ For ill-conditioned matrices it's recommended to use qr_solve() instead
567
+ of lu_solve(). This does not help with input errors however, it just avoids
568
+ to add additional errors.
569
+
570
+ Definition: cond(A) = ||A|| * ||A**-1||
571
+ """
572
+ if norm is None:
573
+ norm = lambda x: ctx.mnorm(x,1)
574
+ return norm(A) * norm(ctx.inverse(A))
575
+
576
+ def lu_solve_mat(ctx, a, b):
577
+ """Solve a * x = b where a and b are matrices."""
578
+ r = ctx.matrix(a.rows, b.cols)
579
+ for i in range(b.cols):
580
+ c = ctx.lu_solve(a, b.column(i))
581
+ for j in range(len(c)):
582
+ r[j, i] = c[j]
583
+ return r
584
+
585
+ def qr(ctx, A, mode = 'full', edps = 10):
586
+ """
587
+ Compute a QR factorization $A = QR$ where
588
+ A is an m x n matrix of real or complex numbers where m >= n
589
+
590
+ mode has following meanings:
591
+ (1) mode = 'raw' returns two matrixes (A, tau) in the
592
+ internal format used by LAPACK
593
+ (2) mode = 'skinny' returns the leading n columns of Q
594
+ and n rows of R
595
+ (3) Any other value returns the leading m columns of Q
596
+ and m rows of R
597
+
598
+ edps is the increase in mp precision used for calculations
599
+
600
+ **Examples**
601
+
602
+ >>> from mpmath import *
603
+ >>> mp.dps = 15
604
+ >>> mp.pretty = True
605
+ >>> A = matrix([[1, 2], [3, 4], [1, 1]])
606
+ >>> Q, R = qr(A)
607
+ >>> Q
608
+ [-0.301511344577764 0.861640436855329 0.408248290463863]
609
+ [-0.904534033733291 -0.123091490979333 -0.408248290463863]
610
+ [-0.301511344577764 -0.492365963917331 0.816496580927726]
611
+ >>> R
612
+ [-3.3166247903554 -4.52267016866645]
613
+ [ 0.0 0.738548945875996]
614
+ [ 0.0 0.0]
615
+ >>> Q * R
616
+ [1.0 2.0]
617
+ [3.0 4.0]
618
+ [1.0 1.0]
619
+ >>> chop(Q.T * Q)
620
+ [1.0 0.0 0.0]
621
+ [0.0 1.0 0.0]
622
+ [0.0 0.0 1.0]
623
+ >>> B = matrix([[1+0j, 2-3j], [3+j, 4+5j]])
624
+ >>> Q, R = qr(B)
625
+ >>> nprint(Q)
626
+ [ (-0.301511 + 0.0j) (0.0695795 - 0.95092j)]
627
+ [(-0.904534 - 0.301511j) (-0.115966 + 0.278318j)]
628
+ >>> nprint(R)
629
+ [(-3.31662 + 0.0j) (-5.72872 - 2.41209j)]
630
+ [ 0.0 (3.91965 + 0.0j)]
631
+ >>> Q * R
632
+ [(1.0 + 0.0j) (2.0 - 3.0j)]
633
+ [(3.0 + 1.0j) (4.0 + 5.0j)]
634
+ >>> chop(Q.T * Q.conjugate())
635
+ [1.0 0.0]
636
+ [0.0 1.0]
637
+
638
+ """
639
+
640
+ # check values before continuing
641
+ assert isinstance(A, ctx.matrix)
642
+ m = A.rows
643
+ n = A.cols
644
+ assert n >= 0
645
+ assert m >= n
646
+ assert edps >= 0
647
+
648
+ # check for complex data type
649
+ cmplx = any(type(x) is ctx.mpc for x in A)
650
+
651
+ # temporarily increase the precision and initialize
652
+ with ctx.extradps(edps):
653
+ tau = ctx.matrix(n,1)
654
+ A = A.copy()
655
+
656
+ # ---------------
657
+ # FACTOR MATRIX A
658
+ # ---------------
659
+ if cmplx:
660
+ one = ctx.mpc('1.0', '0.0')
661
+ zero = ctx.mpc('0.0', '0.0')
662
+ rzero = ctx.mpf('0.0')
663
+
664
+ # main loop to factor A (complex)
665
+ for j in xrange(0, n):
666
+ alpha = A[j,j]
667
+ alphr = ctx.re(alpha)
668
+ alphi = ctx.im(alpha)
669
+
670
+ if (m-j) >= 2:
671
+ xnorm = ctx.fsum( A[i,j]*ctx.conj(A[i,j]) for i in xrange(j+1, m) )
672
+ xnorm = ctx.re( ctx.sqrt(xnorm) )
673
+ else:
674
+ xnorm = rzero
675
+
676
+ if (xnorm == rzero) and (alphi == rzero):
677
+ tau[j] = zero
678
+ continue
679
+
680
+ if alphr < rzero:
681
+ beta = ctx.sqrt(alphr**2 + alphi**2 + xnorm**2)
682
+ else:
683
+ beta = -ctx.sqrt(alphr**2 + alphi**2 + xnorm**2)
684
+
685
+ tau[j] = ctx.mpc( (beta - alphr) / beta, -alphi / beta )
686
+ t = -ctx.conj(tau[j])
687
+ za = one / (alpha - beta)
688
+
689
+ for i in xrange(j+1, m):
690
+ A[i,j] *= za
691
+
692
+ A[j,j] = one
693
+ for k in xrange(j+1, n):
694
+ y = ctx.fsum(A[i,j] * ctx.conj(A[i,k]) for i in xrange(j, m))
695
+ temp = t * ctx.conj(y)
696
+ for i in xrange(j, m):
697
+ A[i,k] += A[i,j] * temp
698
+
699
+ A[j,j] = ctx.mpc(beta, '0.0')
700
+ else:
701
+ one = ctx.mpf('1.0')
702
+ zero = ctx.mpf('0.0')
703
+
704
+ # main loop to factor A (real)
705
+ for j in xrange(0, n):
706
+ alpha = A[j,j]
707
+
708
+ if (m-j) > 2:
709
+ xnorm = ctx.fsum( (A[i,j])**2 for i in xrange(j+1, m) )
710
+ xnorm = ctx.sqrt(xnorm)
711
+ elif (m-j) == 2:
712
+ xnorm = abs( A[m-1,j] )
713
+ else:
714
+ xnorm = zero
715
+
716
+ if xnorm == zero:
717
+ tau[j] = zero
718
+ continue
719
+
720
+ if alpha < zero:
721
+ beta = ctx.sqrt(alpha**2 + xnorm**2)
722
+ else:
723
+ beta = -ctx.sqrt(alpha**2 + xnorm**2)
724
+
725
+ tau[j] = (beta - alpha) / beta
726
+ t = -tau[j]
727
+ da = one / (alpha - beta)
728
+
729
+ for i in xrange(j+1, m):
730
+ A[i,j] *= da
731
+
732
+ A[j,j] = one
733
+ for k in xrange(j+1, n):
734
+ y = ctx.fsum( A[i,j] * A[i,k] for i in xrange(j, m) )
735
+ temp = t * y
736
+ for i in xrange(j,m):
737
+ A[i,k] += A[i,j] * temp
738
+
739
+ A[j,j] = beta
740
+
741
+ # return factorization in same internal format as LAPACK
742
+ if (mode == 'raw') or (mode == 'RAW'):
743
+ return A, tau
744
+
745
+ # ----------------------------------
746
+ # FORM Q USING BACKWARD ACCUMULATION
747
+ # ----------------------------------
748
+
749
+ # form R before the values are overwritten
750
+ R = A.copy()
751
+ for j in xrange(0, n):
752
+ for i in xrange(j+1, m):
753
+ R[i,j] = zero
754
+
755
+ # set the value of p (number of columns of Q to return)
756
+ p = m
757
+ if (mode == 'skinny') or (mode == 'SKINNY'):
758
+ p = n
759
+
760
+ # add columns to A if needed and initialize
761
+ A.cols += (p-n)
762
+ for j in xrange(0, p):
763
+ A[j,j] = one
764
+ for i in xrange(0, j):
765
+ A[i,j] = zero
766
+
767
+ # main loop to form Q
768
+ for j in xrange(n-1, -1, -1):
769
+ t = -tau[j]
770
+ A[j,j] += t
771
+
772
+ for k in xrange(j+1, p):
773
+ if cmplx:
774
+ y = ctx.fsum(A[i,j] * ctx.conj(A[i,k]) for i in xrange(j+1, m))
775
+ temp = t * ctx.conj(y)
776
+ else:
777
+ y = ctx.fsum(A[i,j] * A[i,k] for i in xrange(j+1, m))
778
+ temp = t * y
779
+ A[j,k] = temp
780
+ for i in xrange(j+1, m):
781
+ A[i,k] += A[i,j] * temp
782
+
783
+ for i in xrange(j+1, m):
784
+ A[i, j] *= t
785
+
786
+ return A, R[0:p,0:n]
787
+
788
+ # ------------------
789
+ # END OF FUNCTION QR
790
+ # ------------------
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/matrices.py ADDED
@@ -0,0 +1,1005 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..libmp.backend import xrange
2
+ import warnings
3
+
4
+ # TODO: interpret list as vectors (for multiplication)
5
+
6
+ rowsep = '\n'
7
+ colsep = ' '
8
+
9
+ class _matrix(object):
10
+ """
11
+ Numerical matrix.
12
+
13
+ Specify the dimensions or the data as a nested list.
14
+ Elements default to zero.
15
+ Use a flat list to create a column vector easily.
16
+
17
+ The datatype of the context (mpf for mp, mpi for iv, and float for fp) is used to store the data.
18
+
19
+ Creating matrices
20
+ -----------------
21
+
22
+ Matrices in mpmath are implemented using dictionaries. Only non-zero values
23
+ are stored, so it is cheap to represent sparse matrices.
24
+
25
+ The most basic way to create one is to use the ``matrix`` class directly.
26
+ You can create an empty matrix specifying the dimensions:
27
+
28
+ >>> from mpmath import *
29
+ >>> mp.dps = 15
30
+ >>> matrix(2)
31
+ matrix(
32
+ [['0.0', '0.0'],
33
+ ['0.0', '0.0']])
34
+ >>> matrix(2, 3)
35
+ matrix(
36
+ [['0.0', '0.0', '0.0'],
37
+ ['0.0', '0.0', '0.0']])
38
+
39
+ Calling ``matrix`` with one dimension will create a square matrix.
40
+
41
+ To access the dimensions of a matrix, use the ``rows`` or ``cols`` keyword:
42
+
43
+ >>> A = matrix(3, 2)
44
+ >>> A
45
+ matrix(
46
+ [['0.0', '0.0'],
47
+ ['0.0', '0.0'],
48
+ ['0.0', '0.0']])
49
+ >>> A.rows
50
+ 3
51
+ >>> A.cols
52
+ 2
53
+
54
+ You can also change the dimension of an existing matrix. This will set the
55
+ new elements to 0. If the new dimension is smaller than before, the
56
+ concerning elements are discarded:
57
+
58
+ >>> A.rows = 2
59
+ >>> A
60
+ matrix(
61
+ [['0.0', '0.0'],
62
+ ['0.0', '0.0']])
63
+
64
+ Internally ``mpmathify`` is used every time an element is set. This
65
+ is done using the syntax A[row,column], counting from 0:
66
+
67
+ >>> A = matrix(2)
68
+ >>> A[1,1] = 1 + 1j
69
+ >>> A
70
+ matrix(
71
+ [['0.0', '0.0'],
72
+ ['0.0', mpc(real='1.0', imag='1.0')]])
73
+
74
+ A more comfortable way to create a matrix lets you use nested lists:
75
+
76
+ >>> matrix([[1, 2], [3, 4]])
77
+ matrix(
78
+ [['1.0', '2.0'],
79
+ ['3.0', '4.0']])
80
+
81
+ Convenient advanced functions are available for creating various standard
82
+ matrices, see ``zeros``, ``ones``, ``diag``, ``eye``, ``randmatrix`` and
83
+ ``hilbert``.
84
+
85
+ Vectors
86
+ .......
87
+
88
+ Vectors may also be represented by the ``matrix`` class (with rows = 1 or cols = 1).
89
+ For vectors there are some things which make life easier. A column vector can
90
+ be created using a flat list, a row vectors using an almost flat nested list::
91
+
92
+ >>> matrix([1, 2, 3])
93
+ matrix(
94
+ [['1.0'],
95
+ ['2.0'],
96
+ ['3.0']])
97
+ >>> matrix([[1, 2, 3]])
98
+ matrix(
99
+ [['1.0', '2.0', '3.0']])
100
+
101
+ Optionally vectors can be accessed like lists, using only a single index::
102
+
103
+ >>> x = matrix([1, 2, 3])
104
+ >>> x[1]
105
+ mpf('2.0')
106
+ >>> x[1,0]
107
+ mpf('2.0')
108
+
109
+ Other
110
+ .....
111
+
112
+ Like you probably expected, matrices can be printed::
113
+
114
+ >>> print randmatrix(3) # doctest:+SKIP
115
+ [ 0.782963853573023 0.802057689719883 0.427895717335467]
116
+ [0.0541876859348597 0.708243266653103 0.615134039977379]
117
+ [ 0.856151514955773 0.544759264818486 0.686210904770947]
118
+
119
+ Use ``nstr`` or ``nprint`` to specify the number of digits to print::
120
+
121
+ >>> nprint(randmatrix(5), 3) # doctest:+SKIP
122
+ [2.07e-1 1.66e-1 5.06e-1 1.89e-1 8.29e-1]
123
+ [6.62e-1 6.55e-1 4.47e-1 4.82e-1 2.06e-2]
124
+ [4.33e-1 7.75e-1 6.93e-2 2.86e-1 5.71e-1]
125
+ [1.01e-1 2.53e-1 6.13e-1 3.32e-1 2.59e-1]
126
+ [1.56e-1 7.27e-2 6.05e-1 6.67e-2 2.79e-1]
127
+
128
+ As matrices are mutable, you will need to copy them sometimes::
129
+
130
+ >>> A = matrix(2)
131
+ >>> A
132
+ matrix(
133
+ [['0.0', '0.0'],
134
+ ['0.0', '0.0']])
135
+ >>> B = A.copy()
136
+ >>> B[0,0] = 1
137
+ >>> B
138
+ matrix(
139
+ [['1.0', '0.0'],
140
+ ['0.0', '0.0']])
141
+ >>> A
142
+ matrix(
143
+ [['0.0', '0.0'],
144
+ ['0.0', '0.0']])
145
+
146
+ Finally, it is possible to convert a matrix to a nested list. This is very useful,
147
+ as most Python libraries involving matrices or arrays (namely NumPy or SymPy)
148
+ support this format::
149
+
150
+ >>> B.tolist()
151
+ [[mpf('1.0'), mpf('0.0')], [mpf('0.0'), mpf('0.0')]]
152
+
153
+
154
+ Matrix operations
155
+ -----------------
156
+
157
+ You can add and subtract matrices of compatible dimensions::
158
+
159
+ >>> A = matrix([[1, 2], [3, 4]])
160
+ >>> B = matrix([[-2, 4], [5, 9]])
161
+ >>> A + B
162
+ matrix(
163
+ [['-1.0', '6.0'],
164
+ ['8.0', '13.0']])
165
+ >>> A - B
166
+ matrix(
167
+ [['3.0', '-2.0'],
168
+ ['-2.0', '-5.0']])
169
+ >>> A + ones(3) # doctest:+ELLIPSIS
170
+ Traceback (most recent call last):
171
+ ...
172
+ ValueError: incompatible dimensions for addition
173
+
174
+ It is possible to multiply or add matrices and scalars. In the latter case the
175
+ operation will be done element-wise::
176
+
177
+ >>> A * 2
178
+ matrix(
179
+ [['2.0', '4.0'],
180
+ ['6.0', '8.0']])
181
+ >>> A / 4
182
+ matrix(
183
+ [['0.25', '0.5'],
184
+ ['0.75', '1.0']])
185
+ >>> A - 1
186
+ matrix(
187
+ [['0.0', '1.0'],
188
+ ['2.0', '3.0']])
189
+
190
+ Of course you can perform matrix multiplication, if the dimensions are
191
+ compatible, using ``@`` (for Python >= 3.5) or ``*``. For clarity, ``@`` is
192
+ recommended (`PEP 465 <https://www.python.org/dev/peps/pep-0465/>`), because
193
+ the meaning of ``*`` is different in many other Python libraries such as NumPy.
194
+
195
+ >>> A @ B # doctest:+SKIP
196
+ matrix(
197
+ [['8.0', '22.0'],
198
+ ['14.0', '48.0']])
199
+ >>> A * B # same as A @ B
200
+ matrix(
201
+ [['8.0', '22.0'],
202
+ ['14.0', '48.0']])
203
+ >>> matrix([[1, 2, 3]]) * matrix([[-6], [7], [-2]])
204
+ matrix(
205
+ [['2.0']])
206
+
207
+ ..
208
+ COMMENT: TODO: the above "doctest:+SKIP" may be removed as soon as we
209
+ have dropped support for Python 3.5 and below.
210
+
211
+ You can raise powers of square matrices::
212
+
213
+ >>> A**2
214
+ matrix(
215
+ [['7.0', '10.0'],
216
+ ['15.0', '22.0']])
217
+
218
+ Negative powers will calculate the inverse::
219
+
220
+ >>> A**-1
221
+ matrix(
222
+ [['-2.0', '1.0'],
223
+ ['1.5', '-0.5']])
224
+ >>> A * A**-1
225
+ matrix(
226
+ [['1.0', '1.0842021724855e-19'],
227
+ ['-2.16840434497101e-19', '1.0']])
228
+
229
+
230
+
231
+ Matrix transposition is straightforward::
232
+
233
+ >>> A = ones(2, 3)
234
+ >>> A
235
+ matrix(
236
+ [['1.0', '1.0', '1.0'],
237
+ ['1.0', '1.0', '1.0']])
238
+ >>> A.T
239
+ matrix(
240
+ [['1.0', '1.0'],
241
+ ['1.0', '1.0'],
242
+ ['1.0', '1.0']])
243
+
244
+ Norms
245
+ .....
246
+
247
+ Sometimes you need to know how "large" a matrix or vector is. Due to their
248
+ multidimensional nature it's not possible to compare them, but there are
249
+ several functions to map a matrix or a vector to a positive real number, the
250
+ so called norms.
251
+
252
+ For vectors the p-norm is intended, usually the 1-, the 2- and the oo-norm are
253
+ used.
254
+
255
+ >>> x = matrix([-10, 2, 100])
256
+ >>> norm(x, 1)
257
+ mpf('112.0')
258
+ >>> norm(x, 2)
259
+ mpf('100.5186549850325')
260
+ >>> norm(x, inf)
261
+ mpf('100.0')
262
+
263
+ Please note that the 2-norm is the most used one, though it is more expensive
264
+ to calculate than the 1- or oo-norm.
265
+
266
+ It is possible to generalize some vector norms to matrix norm::
267
+
268
+ >>> A = matrix([[1, -1000], [100, 50]])
269
+ >>> mnorm(A, 1)
270
+ mpf('1050.0')
271
+ >>> mnorm(A, inf)
272
+ mpf('1001.0')
273
+ >>> mnorm(A, 'F')
274
+ mpf('1006.2310867787777')
275
+
276
+ The last norm (the "Frobenius-norm") is an approximation for the 2-norm, which
277
+ is hard to calculate and not available. The Frobenius-norm lacks some
278
+ mathematical properties you might expect from a norm.
279
+ """
280
+
281
+ def __init__(self, *args, **kwargs):
282
+ self.__data = {}
283
+ # LU decompostion cache, this is useful when solving the same system
284
+ # multiple times, when calculating the inverse and when calculating the
285
+ # determinant
286
+ self._LU = None
287
+ if "force_type" in kwargs:
288
+ warnings.warn("The force_type argument was removed, it did not work"
289
+ " properly anyway. If you want to force floating-point or"
290
+ " interval computations, use the respective methods from `fp`"
291
+ " or `mp` instead, e.g., `fp.matrix()` or `iv.matrix()`."
292
+ " If you want to truncate values to integer, use .apply(int) instead.")
293
+ if isinstance(args[0], (list, tuple)):
294
+ if isinstance(args[0][0], (list, tuple)):
295
+ # interpret nested list as matrix
296
+ A = args[0]
297
+ self.__rows = len(A)
298
+ self.__cols = len(A[0])
299
+ for i, row in enumerate(A):
300
+ for j, a in enumerate(row):
301
+ # note: this will call __setitem__ which will call self.ctx.convert() to convert the datatype.
302
+ self[i, j] = a
303
+ else:
304
+ # interpret list as row vector
305
+ v = args[0]
306
+ self.__rows = len(v)
307
+ self.__cols = 1
308
+ for i, e in enumerate(v):
309
+ self[i, 0] = e
310
+ elif isinstance(args[0], int):
311
+ # create empty matrix of given dimensions
312
+ if len(args) == 1:
313
+ self.__rows = self.__cols = args[0]
314
+ else:
315
+ if not isinstance(args[1], int):
316
+ raise TypeError("expected int")
317
+ self.__rows = args[0]
318
+ self.__cols = args[1]
319
+ elif isinstance(args[0], _matrix):
320
+ A = args[0]
321
+ self.__rows = A._matrix__rows
322
+ self.__cols = A._matrix__cols
323
+ for i in xrange(A.__rows):
324
+ for j in xrange(A.__cols):
325
+ self[i, j] = A[i, j]
326
+ elif hasattr(args[0], 'tolist'):
327
+ A = self.ctx.matrix(args[0].tolist())
328
+ self.__data = A._matrix__data
329
+ self.__rows = A._matrix__rows
330
+ self.__cols = A._matrix__cols
331
+ else:
332
+ raise TypeError('could not interpret given arguments')
333
+
334
+ def apply(self, f):
335
+ """
336
+ Return a copy of self with the function `f` applied elementwise.
337
+ """
338
+ new = self.ctx.matrix(self.__rows, self.__cols)
339
+ for i in xrange(self.__rows):
340
+ for j in xrange(self.__cols):
341
+ new[i,j] = f(self[i,j])
342
+ return new
343
+
344
+ def __nstr__(self, n=None, **kwargs):
345
+ # Build table of string representations of the elements
346
+ res = []
347
+ # Track per-column max lengths for pretty alignment
348
+ maxlen = [0] * self.cols
349
+ for i in range(self.rows):
350
+ res.append([])
351
+ for j in range(self.cols):
352
+ if n:
353
+ string = self.ctx.nstr(self[i,j], n, **kwargs)
354
+ else:
355
+ string = str(self[i,j])
356
+ res[-1].append(string)
357
+ maxlen[j] = max(len(string), maxlen[j])
358
+ # Patch strings together
359
+ for i, row in enumerate(res):
360
+ for j, elem in enumerate(row):
361
+ # Pad each element up to maxlen so the columns line up
362
+ row[j] = elem.rjust(maxlen[j])
363
+ res[i] = "[" + colsep.join(row) + "]"
364
+ return rowsep.join(res)
365
+
366
+ def __str__(self):
367
+ return self.__nstr__()
368
+
369
+ def _toliststr(self, avoid_type=False):
370
+ """
371
+ Create a list string from a matrix.
372
+
373
+ If avoid_type: avoid multiple 'mpf's.
374
+ """
375
+ # XXX: should be something like self.ctx._types
376
+ typ = self.ctx.mpf
377
+ s = '['
378
+ for i in xrange(self.__rows):
379
+ s += '['
380
+ for j in xrange(self.__cols):
381
+ if not avoid_type or not isinstance(self[i,j], typ):
382
+ a = repr(self[i,j])
383
+ else:
384
+ a = "'" + str(self[i,j]) + "'"
385
+ s += a + ', '
386
+ s = s[:-2]
387
+ s += '],\n '
388
+ s = s[:-3]
389
+ s += ']'
390
+ return s
391
+
392
+ def tolist(self):
393
+ """
394
+ Convert the matrix to a nested list.
395
+ """
396
+ return [[self[i,j] for j in range(self.__cols)] for i in range(self.__rows)]
397
+
398
+ def __repr__(self):
399
+ if self.ctx.pretty:
400
+ return self.__str__()
401
+ s = 'matrix(\n'
402
+ s += self._toliststr(avoid_type=True) + ')'
403
+ return s
404
+
405
+ def __get_element(self, key):
406
+ '''
407
+ Fast extraction of the i,j element from the matrix
408
+ This function is for private use only because is unsafe:
409
+ 1. Does not check on the value of key it expects key to be a integer tuple (i,j)
410
+ 2. Does not check bounds
411
+ '''
412
+ if key in self.__data:
413
+ return self.__data[key]
414
+ else:
415
+ return self.ctx.zero
416
+
417
+ def __set_element(self, key, value):
418
+ '''
419
+ Fast assignment of the i,j element in the matrix
420
+ This function is unsafe:
421
+ 1. Does not check on the value of key it expects key to be a integer tuple (i,j)
422
+ 2. Does not check bounds
423
+ 3. Does not check the value type
424
+ 4. Does not reset the LU cache
425
+ '''
426
+ if value: # only store non-zeros
427
+ self.__data[key] = value
428
+ elif key in self.__data:
429
+ del self.__data[key]
430
+
431
+
432
+ def __getitem__(self, key):
433
+ '''
434
+ Getitem function for mp matrix class with slice index enabled
435
+ it allows the following assingments
436
+ scalar to a slice of the matrix
437
+ B = A[:,2:6]
438
+ '''
439
+ # Convert vector to matrix indexing
440
+ if isinstance(key, int) or isinstance(key,slice):
441
+ # only sufficent for vectors
442
+ if self.__rows == 1:
443
+ key = (0, key)
444
+ elif self.__cols == 1:
445
+ key = (key, 0)
446
+ else:
447
+ raise IndexError('insufficient indices for matrix')
448
+
449
+ if isinstance(key[0],slice) or isinstance(key[1],slice):
450
+
451
+ #Rows
452
+ if isinstance(key[0],slice):
453
+ #Check bounds
454
+ if (key[0].start is None or key[0].start >= 0) and \
455
+ (key[0].stop is None or key[0].stop <= self.__rows+1):
456
+ # Generate indices
457
+ rows = xrange(*key[0].indices(self.__rows))
458
+ else:
459
+ raise IndexError('Row index out of bounds')
460
+ else:
461
+ # Single row
462
+ rows = [key[0]]
463
+
464
+ # Columns
465
+ if isinstance(key[1],slice):
466
+ # Check bounds
467
+ if (key[1].start is None or key[1].start >= 0) and \
468
+ (key[1].stop is None or key[1].stop <= self.__cols+1):
469
+ # Generate indices
470
+ columns = xrange(*key[1].indices(self.__cols))
471
+ else:
472
+ raise IndexError('Column index out of bounds')
473
+
474
+ else:
475
+ # Single column
476
+ columns = [key[1]]
477
+
478
+ # Create matrix slice
479
+ m = self.ctx.matrix(len(rows),len(columns))
480
+
481
+ # Assign elements to the output matrix
482
+ for i,x in enumerate(rows):
483
+ for j,y in enumerate(columns):
484
+ m.__set_element((i,j),self.__get_element((x,y)))
485
+
486
+ return m
487
+
488
+ else:
489
+ # single element extraction
490
+ if key[0] >= self.__rows or key[1] >= self.__cols:
491
+ raise IndexError('matrix index out of range')
492
+ if key in self.__data:
493
+ return self.__data[key]
494
+ else:
495
+ return self.ctx.zero
496
+
497
+ def __setitem__(self, key, value):
498
+ # setitem function for mp matrix class with slice index enabled
499
+ # it allows the following assingments
500
+ # scalar to a slice of the matrix
501
+ # A[:,2:6] = 2.5
502
+ # submatrix to matrix (the value matrix should be the same size as the slice size)
503
+ # A[3,:] = B where A is n x m and B is n x 1
504
+ # Convert vector to matrix indexing
505
+ if isinstance(key, int) or isinstance(key,slice):
506
+ # only sufficent for vectors
507
+ if self.__rows == 1:
508
+ key = (0, key)
509
+ elif self.__cols == 1:
510
+ key = (key, 0)
511
+ else:
512
+ raise IndexError('insufficient indices for matrix')
513
+ # Slice indexing
514
+ if isinstance(key[0],slice) or isinstance(key[1],slice):
515
+ # Rows
516
+ if isinstance(key[0],slice):
517
+ # Check bounds
518
+ if (key[0].start is None or key[0].start >= 0) and \
519
+ (key[0].stop is None or key[0].stop <= self.__rows+1):
520
+ # generate row indices
521
+ rows = xrange(*key[0].indices(self.__rows))
522
+ else:
523
+ raise IndexError('Row index out of bounds')
524
+ else:
525
+ # Single row
526
+ rows = [key[0]]
527
+ # Columns
528
+ if isinstance(key[1],slice):
529
+ # Check bounds
530
+ if (key[1].start is None or key[1].start >= 0) and \
531
+ (key[1].stop is None or key[1].stop <= self.__cols+1):
532
+ # Generate column indices
533
+ columns = xrange(*key[1].indices(self.__cols))
534
+ else:
535
+ raise IndexError('Column index out of bounds')
536
+ else:
537
+ # Single column
538
+ columns = [key[1]]
539
+ # Assign slice with a scalar
540
+ if isinstance(value,self.ctx.matrix):
541
+ # Assign elements to matrix if input and output dimensions match
542
+ if len(rows) == value.rows and len(columns) == value.cols:
543
+ for i,x in enumerate(rows):
544
+ for j,y in enumerate(columns):
545
+ self.__set_element((x,y), value.__get_element((i,j)))
546
+ else:
547
+ raise ValueError('Dimensions do not match')
548
+ else:
549
+ # Assign slice with scalars
550
+ value = self.ctx.convert(value)
551
+ for i in rows:
552
+ for j in columns:
553
+ self.__set_element((i,j), value)
554
+ else:
555
+ # Single element assingment
556
+ # Check bounds
557
+ if key[0] >= self.__rows or key[1] >= self.__cols:
558
+ raise IndexError('matrix index out of range')
559
+ # Convert and store value
560
+ value = self.ctx.convert(value)
561
+ if value: # only store non-zeros
562
+ self.__data[key] = value
563
+ elif key in self.__data:
564
+ del self.__data[key]
565
+
566
+ if self._LU:
567
+ self._LU = None
568
+ return
569
+
570
+ def __iter__(self):
571
+ for i in xrange(self.__rows):
572
+ for j in xrange(self.__cols):
573
+ yield self[i,j]
574
+
575
+ def __mul__(self, other):
576
+ if isinstance(other, self.ctx.matrix):
577
+ # dot multiplication
578
+ if self.__cols != other.__rows:
579
+ raise ValueError('dimensions not compatible for multiplication')
580
+ new = self.ctx.matrix(self.__rows, other.__cols)
581
+ self_zero = self.ctx.zero
582
+ self_get = self.__data.get
583
+ other_zero = other.ctx.zero
584
+ other_get = other.__data.get
585
+ for i in xrange(self.__rows):
586
+ for j in xrange(other.__cols):
587
+ new[i, j] = self.ctx.fdot((self_get((i,k), self_zero), other_get((k,j), other_zero))
588
+ for k in xrange(other.__rows))
589
+ return new
590
+ else:
591
+ # try scalar multiplication
592
+ new = self.ctx.matrix(self.__rows, self.__cols)
593
+ for i in xrange(self.__rows):
594
+ for j in xrange(self.__cols):
595
+ new[i, j] = other * self[i, j]
596
+ return new
597
+
598
+ def __matmul__(self, other):
599
+ return self.__mul__(other)
600
+
601
+ def __rmul__(self, other):
602
+ # assume other is scalar and thus commutative
603
+ if isinstance(other, self.ctx.matrix):
604
+ raise TypeError("other should not be type of ctx.matrix")
605
+ return self.__mul__(other)
606
+
607
+ def __pow__(self, other):
608
+ # avoid cyclic import problems
609
+ #from linalg import inverse
610
+ if not isinstance(other, int):
611
+ raise ValueError('only integer exponents are supported')
612
+ if not self.__rows == self.__cols:
613
+ raise ValueError('only powers of square matrices are defined')
614
+ n = other
615
+ if n == 0:
616
+ return self.ctx.eye(self.__rows)
617
+ if n < 0:
618
+ n = -n
619
+ neg = True
620
+ else:
621
+ neg = False
622
+ i = n
623
+ y = 1
624
+ z = self.copy()
625
+ while i != 0:
626
+ if i % 2 == 1:
627
+ y = y * z
628
+ z = z*z
629
+ i = i // 2
630
+ if neg:
631
+ y = self.ctx.inverse(y)
632
+ return y
633
+
634
+ def __div__(self, other):
635
+ # assume other is scalar and do element-wise divison
636
+ assert not isinstance(other, self.ctx.matrix)
637
+ new = self.ctx.matrix(self.__rows, self.__cols)
638
+ for i in xrange(self.__rows):
639
+ for j in xrange(self.__cols):
640
+ new[i,j] = self[i,j] / other
641
+ return new
642
+
643
+ __truediv__ = __div__
644
+
645
+ def __add__(self, other):
646
+ if isinstance(other, self.ctx.matrix):
647
+ if not (self.__rows == other.__rows and self.__cols == other.__cols):
648
+ raise ValueError('incompatible dimensions for addition')
649
+ new = self.ctx.matrix(self.__rows, self.__cols)
650
+ for i in xrange(self.__rows):
651
+ for j in xrange(self.__cols):
652
+ new[i,j] = self[i,j] + other[i,j]
653
+ return new
654
+ else:
655
+ # assume other is scalar and add element-wise
656
+ new = self.ctx.matrix(self.__rows, self.__cols)
657
+ for i in xrange(self.__rows):
658
+ for j in xrange(self.__cols):
659
+ new[i,j] += self[i,j] + other
660
+ return new
661
+
662
+ def __radd__(self, other):
663
+ return self.__add__(other)
664
+
665
+ def __sub__(self, other):
666
+ if isinstance(other, self.ctx.matrix) and not (self.__rows == other.__rows
667
+ and self.__cols == other.__cols):
668
+ raise ValueError('incompatible dimensions for subtraction')
669
+ return self.__add__(other * (-1))
670
+
671
+ def __pos__(self):
672
+ """
673
+ +M returns a copy of M, rounded to current working precision.
674
+ """
675
+ return (+1) * self
676
+
677
+ def __neg__(self):
678
+ return (-1) * self
679
+
680
+ def __rsub__(self, other):
681
+ return -self + other
682
+
683
+ def __eq__(self, other):
684
+ return self.__rows == other.__rows and self.__cols == other.__cols \
685
+ and self.__data == other.__data
686
+
687
+ def __len__(self):
688
+ if self.rows == 1:
689
+ return self.cols
690
+ elif self.cols == 1:
691
+ return self.rows
692
+ else:
693
+ return self.rows # do it like numpy
694
+
695
+ def __getrows(self):
696
+ return self.__rows
697
+
698
+ def __setrows(self, value):
699
+ for key in self.__data.copy():
700
+ if key[0] >= value:
701
+ del self.__data[key]
702
+ self.__rows = value
703
+
704
+ rows = property(__getrows, __setrows, doc='number of rows')
705
+
706
+ def __getcols(self):
707
+ return self.__cols
708
+
709
+ def __setcols(self, value):
710
+ for key in self.__data.copy():
711
+ if key[1] >= value:
712
+ del self.__data[key]
713
+ self.__cols = value
714
+
715
+ cols = property(__getcols, __setcols, doc='number of columns')
716
+
717
+ def transpose(self):
718
+ new = self.ctx.matrix(self.__cols, self.__rows)
719
+ for i in xrange(self.__rows):
720
+ for j in xrange(self.__cols):
721
+ new[j,i] = self[i,j]
722
+ return new
723
+
724
+ T = property(transpose)
725
+
726
+ def conjugate(self):
727
+ return self.apply(self.ctx.conj)
728
+
729
+ def transpose_conj(self):
730
+ return self.conjugate().transpose()
731
+
732
+ H = property(transpose_conj)
733
+
734
+ def copy(self):
735
+ new = self.ctx.matrix(self.__rows, self.__cols)
736
+ new.__data = self.__data.copy()
737
+ return new
738
+
739
+ __copy__ = copy
740
+
741
+ def column(self, n):
742
+ m = self.ctx.matrix(self.rows, 1)
743
+ for i in range(self.rows):
744
+ m[i] = self[i,n]
745
+ return m
746
+
747
+ class MatrixMethods(object):
748
+
749
+ def __init__(ctx):
750
+ # XXX: subclass
751
+ ctx.matrix = type('matrix', (_matrix,), {})
752
+ ctx.matrix.ctx = ctx
753
+ ctx.matrix.convert = ctx.convert
754
+
755
+ def eye(ctx, n, **kwargs):
756
+ """
757
+ Create square identity matrix n x n.
758
+ """
759
+ A = ctx.matrix(n, **kwargs)
760
+ for i in xrange(n):
761
+ A[i,i] = 1
762
+ return A
763
+
764
+ def diag(ctx, diagonal, **kwargs):
765
+ """
766
+ Create square diagonal matrix using given list.
767
+
768
+ Example:
769
+ >>> from mpmath import diag, mp
770
+ >>> mp.pretty = False
771
+ >>> diag([1, 2, 3])
772
+ matrix(
773
+ [['1.0', '0.0', '0.0'],
774
+ ['0.0', '2.0', '0.0'],
775
+ ['0.0', '0.0', '3.0']])
776
+ """
777
+ A = ctx.matrix(len(diagonal), **kwargs)
778
+ for i in xrange(len(diagonal)):
779
+ A[i,i] = diagonal[i]
780
+ return A
781
+
782
+ def zeros(ctx, *args, **kwargs):
783
+ """
784
+ Create matrix m x n filled with zeros.
785
+ One given dimension will create square matrix n x n.
786
+
787
+ Example:
788
+ >>> from mpmath import zeros, mp
789
+ >>> mp.pretty = False
790
+ >>> zeros(2)
791
+ matrix(
792
+ [['0.0', '0.0'],
793
+ ['0.0', '0.0']])
794
+ """
795
+ if len(args) == 1:
796
+ m = n = args[0]
797
+ elif len(args) == 2:
798
+ m = args[0]
799
+ n = args[1]
800
+ else:
801
+ raise TypeError('zeros expected at most 2 arguments, got %i' % len(args))
802
+ A = ctx.matrix(m, n, **kwargs)
803
+ for i in xrange(m):
804
+ for j in xrange(n):
805
+ A[i,j] = 0
806
+ return A
807
+
808
+ def ones(ctx, *args, **kwargs):
809
+ """
810
+ Create matrix m x n filled with ones.
811
+ One given dimension will create square matrix n x n.
812
+
813
+ Example:
814
+ >>> from mpmath import ones, mp
815
+ >>> mp.pretty = False
816
+ >>> ones(2)
817
+ matrix(
818
+ [['1.0', '1.0'],
819
+ ['1.0', '1.0']])
820
+ """
821
+ if len(args) == 1:
822
+ m = n = args[0]
823
+ elif len(args) == 2:
824
+ m = args[0]
825
+ n = args[1]
826
+ else:
827
+ raise TypeError('ones expected at most 2 arguments, got %i' % len(args))
828
+ A = ctx.matrix(m, n, **kwargs)
829
+ for i in xrange(m):
830
+ for j in xrange(n):
831
+ A[i,j] = 1
832
+ return A
833
+
834
+ def hilbert(ctx, m, n=None):
835
+ """
836
+ Create (pseudo) hilbert matrix m x n.
837
+ One given dimension will create hilbert matrix n x n.
838
+
839
+ The matrix is very ill-conditioned and symmetric, positive definite if
840
+ square.
841
+ """
842
+ if n is None:
843
+ n = m
844
+ A = ctx.matrix(m, n)
845
+ for i in xrange(m):
846
+ for j in xrange(n):
847
+ A[i,j] = ctx.one / (i + j + 1)
848
+ return A
849
+
850
+ def randmatrix(ctx, m, n=None, min=0, max=1, **kwargs):
851
+ """
852
+ Create a random m x n matrix.
853
+
854
+ All values are >= min and <max.
855
+ n defaults to m.
856
+
857
+ Example:
858
+ >>> from mpmath import randmatrix
859
+ >>> randmatrix(2) # doctest:+SKIP
860
+ matrix(
861
+ [['0.53491598236191806', '0.57195669543302752'],
862
+ ['0.85589992269513615', '0.82444367501382143']])
863
+ """
864
+ if not n:
865
+ n = m
866
+ A = ctx.matrix(m, n, **kwargs)
867
+ for i in xrange(m):
868
+ for j in xrange(n):
869
+ A[i,j] = ctx.rand() * (max - min) + min
870
+ return A
871
+
872
+ def swap_row(ctx, A, i, j):
873
+ """
874
+ Swap row i with row j.
875
+ """
876
+ if i == j:
877
+ return
878
+ if isinstance(A, ctx.matrix):
879
+ for k in xrange(A.cols):
880
+ A[i,k], A[j,k] = A[j,k], A[i,k]
881
+ elif isinstance(A, list):
882
+ A[i], A[j] = A[j], A[i]
883
+ else:
884
+ raise TypeError('could not interpret type')
885
+
886
+ def extend(ctx, A, b):
887
+ """
888
+ Extend matrix A with column b and return result.
889
+ """
890
+ if not isinstance(A, ctx.matrix):
891
+ raise TypeError("A should be a type of ctx.matrix")
892
+ if A.rows != len(b):
893
+ raise ValueError("Value should be equal to len(b)")
894
+ A = A.copy()
895
+ A.cols += 1
896
+ for i in xrange(A.rows):
897
+ A[i, A.cols-1] = b[i]
898
+ return A
899
+
900
+ def norm(ctx, x, p=2):
901
+ r"""
902
+ Gives the entrywise `p`-norm of an iterable *x*, i.e. the vector norm
903
+ `\left(\sum_k |x_k|^p\right)^{1/p}`, for any given `1 \le p \le \infty`.
904
+
905
+ Special cases:
906
+
907
+ If *x* is not iterable, this just returns ``absmax(x)``.
908
+
909
+ ``p=1`` gives the sum of absolute values.
910
+
911
+ ``p=2`` is the standard Euclidean vector norm.
912
+
913
+ ``p=inf`` gives the magnitude of the largest element.
914
+
915
+ For *x* a matrix, ``p=2`` is the Frobenius norm.
916
+ For operator matrix norms, use :func:`~mpmath.mnorm` instead.
917
+
918
+ You can use the string 'inf' as well as float('inf') or mpf('inf')
919
+ to specify the infinity norm.
920
+
921
+ **Examples**
922
+
923
+ >>> from mpmath import *
924
+ >>> mp.dps = 15; mp.pretty = False
925
+ >>> x = matrix([-10, 2, 100])
926
+ >>> norm(x, 1)
927
+ mpf('112.0')
928
+ >>> norm(x, 2)
929
+ mpf('100.5186549850325')
930
+ >>> norm(x, inf)
931
+ mpf('100.0')
932
+
933
+ """
934
+ try:
935
+ iter(x)
936
+ except TypeError:
937
+ return ctx.absmax(x)
938
+ if type(p) is not int:
939
+ p = ctx.convert(p)
940
+ if p == ctx.inf:
941
+ return max(ctx.absmax(i) for i in x)
942
+ elif p == 1:
943
+ return ctx.fsum(x, absolute=1)
944
+ elif p == 2:
945
+ return ctx.sqrt(ctx.fsum(x, absolute=1, squared=1))
946
+ elif p > 1:
947
+ return ctx.nthroot(ctx.fsum(abs(i)**p for i in x), p)
948
+ else:
949
+ raise ValueError('p has to be >= 1')
950
+
951
+ def mnorm(ctx, A, p=1):
952
+ r"""
953
+ Gives the matrix (operator) `p`-norm of A. Currently ``p=1`` and ``p=inf``
954
+ are supported:
955
+
956
+ ``p=1`` gives the 1-norm (maximal column sum)
957
+
958
+ ``p=inf`` gives the `\infty`-norm (maximal row sum).
959
+ You can use the string 'inf' as well as float('inf') or mpf('inf')
960
+
961
+ ``p=2`` (not implemented) for a square matrix is the usual spectral
962
+ matrix norm, i.e. the largest singular value.
963
+
964
+ ``p='f'`` (or 'F', 'fro', 'Frobenius, 'frobenius') gives the
965
+ Frobenius norm, which is the elementwise 2-norm. The Frobenius norm is an
966
+ approximation of the spectral norm and satisfies
967
+
968
+ .. math ::
969
+
970
+ \frac{1}{\sqrt{\mathrm{rank}(A)}} \|A\|_F \le \|A\|_2 \le \|A\|_F
971
+
972
+ The Frobenius norm lacks some mathematical properties that might
973
+ be expected of a norm.
974
+
975
+ For general elementwise `p`-norms, use :func:`~mpmath.norm` instead.
976
+
977
+ **Examples**
978
+
979
+ >>> from mpmath import *
980
+ >>> mp.dps = 15; mp.pretty = False
981
+ >>> A = matrix([[1, -1000], [100, 50]])
982
+ >>> mnorm(A, 1)
983
+ mpf('1050.0')
984
+ >>> mnorm(A, inf)
985
+ mpf('1001.0')
986
+ >>> mnorm(A, 'F')
987
+ mpf('1006.2310867787777')
988
+
989
+ """
990
+ A = ctx.matrix(A)
991
+ if type(p) is not int:
992
+ if type(p) is str and 'frobenius'.startswith(p.lower()):
993
+ return ctx.norm(A, 2)
994
+ p = ctx.convert(p)
995
+ m, n = A.rows, A.cols
996
+ if p == 1:
997
+ return max(ctx.fsum((A[i,j] for i in xrange(m)), absolute=1) for j in xrange(n))
998
+ elif p == ctx.inf:
999
+ return max(ctx.fsum((A[i,j] for j in xrange(n)), absolute=1) for i in xrange(m))
1000
+ else:
1001
+ raise NotImplementedError("matrix p-norm for arbitrary p")
1002
+
1003
+ if __name__ == '__main__':
1004
+ import doctest
1005
+ doctest.testmod()
env-llmeval/lib/python3.10/site-packages/mpmath/visualization.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Plotting (requires matplotlib)
3
+ """
4
+
5
+ from colorsys import hsv_to_rgb, hls_to_rgb
6
+ from .libmp import NoConvergence
7
+ from .libmp.backend import xrange
8
+
9
+ class VisualizationMethods(object):
10
+ plot_ignore = (ValueError, ArithmeticError, ZeroDivisionError, NoConvergence)
11
+
12
+ def plot(ctx, f, xlim=[-5,5], ylim=None, points=200, file=None, dpi=None,
13
+ singularities=[], axes=None):
14
+ r"""
15
+ Shows a simple 2D plot of a function `f(x)` or list of functions
16
+ `[f_0(x), f_1(x), \ldots, f_n(x)]` over a given interval
17
+ specified by *xlim*. Some examples::
18
+
19
+ plot(lambda x: exp(x)*li(x), [1, 4])
20
+ plot([cos, sin], [-4, 4])
21
+ plot([fresnels, fresnelc], [-4, 4])
22
+ plot([sqrt, cbrt], [-4, 4])
23
+ plot(lambda t: zeta(0.5+t*j), [-20, 20])
24
+ plot([floor, ceil, abs, sign], [-5, 5])
25
+
26
+ Points where the function raises a numerical exception or
27
+ returns an infinite value are removed from the graph.
28
+ Singularities can also be excluded explicitly
29
+ as follows (useful for removing erroneous vertical lines)::
30
+
31
+ plot(cot, ylim=[-5, 5]) # bad
32
+ plot(cot, ylim=[-5, 5], singularities=[-pi, 0, pi]) # good
33
+
34
+ For parts where the function assumes complex values, the
35
+ real part is plotted with dashes and the imaginary part
36
+ is plotted with dots.
37
+
38
+ .. note :: This function requires matplotlib (pylab).
39
+ """
40
+ if file:
41
+ axes = None
42
+ fig = None
43
+ if not axes:
44
+ import pylab
45
+ fig = pylab.figure()
46
+ axes = fig.add_subplot(111)
47
+ if not isinstance(f, (tuple, list)):
48
+ f = [f]
49
+ a, b = xlim
50
+ colors = ['b', 'r', 'g', 'm', 'k']
51
+ for n, func in enumerate(f):
52
+ x = ctx.arange(a, b, (b-a)/float(points))
53
+ segments = []
54
+ segment = []
55
+ in_complex = False
56
+ for i in xrange(len(x)):
57
+ try:
58
+ if i != 0:
59
+ for sing in singularities:
60
+ if x[i-1] <= sing and x[i] >= sing:
61
+ raise ValueError
62
+ v = func(x[i])
63
+ if ctx.isnan(v) or abs(v) > 1e300:
64
+ raise ValueError
65
+ if hasattr(v, "imag") and v.imag:
66
+ re = float(v.real)
67
+ im = float(v.imag)
68
+ if not in_complex:
69
+ in_complex = True
70
+ segments.append(segment)
71
+ segment = []
72
+ segment.append((float(x[i]), re, im))
73
+ else:
74
+ if in_complex:
75
+ in_complex = False
76
+ segments.append(segment)
77
+ segment = []
78
+ if hasattr(v, "real"):
79
+ v = v.real
80
+ segment.append((float(x[i]), v))
81
+ except ctx.plot_ignore:
82
+ if segment:
83
+ segments.append(segment)
84
+ segment = []
85
+ if segment:
86
+ segments.append(segment)
87
+ for segment in segments:
88
+ x = [s[0] for s in segment]
89
+ y = [s[1] for s in segment]
90
+ if not x:
91
+ continue
92
+ c = colors[n % len(colors)]
93
+ if len(segment[0]) == 3:
94
+ z = [s[2] for s in segment]
95
+ axes.plot(x, y, '--'+c, linewidth=3)
96
+ axes.plot(x, z, ':'+c, linewidth=3)
97
+ else:
98
+ axes.plot(x, y, c, linewidth=3)
99
+ axes.set_xlim([float(_) for _ in xlim])
100
+ if ylim:
101
+ axes.set_ylim([float(_) for _ in ylim])
102
+ axes.set_xlabel('x')
103
+ axes.set_ylabel('f(x)')
104
+ axes.grid(True)
105
+ if fig:
106
+ if file:
107
+ pylab.savefig(file, dpi=dpi)
108
+ else:
109
+ pylab.show()
110
+
111
+ def default_color_function(ctx, z):
112
+ if ctx.isinf(z):
113
+ return (1.0, 1.0, 1.0)
114
+ if ctx.isnan(z):
115
+ return (0.5, 0.5, 0.5)
116
+ pi = 3.1415926535898
117
+ a = (float(ctx.arg(z)) + ctx.pi) / (2*ctx.pi)
118
+ a = (a + 0.5) % 1.0
119
+ b = 1.0 - float(1/(1.0+abs(z)**0.3))
120
+ return hls_to_rgb(a, b, 0.8)
121
+
122
+ blue_orange_colors = [
123
+ (-1.0, (0.0, 0.0, 0.0)),
124
+ (-0.95, (0.1, 0.2, 0.5)), # dark blue
125
+ (-0.5, (0.0, 0.5, 1.0)), # blueish
126
+ (-0.05, (0.4, 0.8, 0.8)), # cyanish
127
+ ( 0.0, (1.0, 1.0, 1.0)),
128
+ ( 0.05, (1.0, 0.9, 0.3)), # yellowish
129
+ ( 0.5, (0.9, 0.5, 0.0)), # orangeish
130
+ ( 0.95, (0.7, 0.1, 0.0)), # redish
131
+ ( 1.0, (0.0, 0.0, 0.0)),
132
+ ( 2.0, (0.0, 0.0, 0.0)),
133
+ ]
134
+
135
+ def phase_color_function(ctx, z):
136
+ if ctx.isinf(z):
137
+ return (1.0, 1.0, 1.0)
138
+ if ctx.isnan(z):
139
+ return (0.5, 0.5, 0.5)
140
+ pi = 3.1415926535898
141
+ w = float(ctx.arg(z)) / pi
142
+ w = max(min(w, 1.0), -1.0)
143
+ for i in range(1,len(blue_orange_colors)):
144
+ if blue_orange_colors[i][0] > w:
145
+ a, (ra, ga, ba) = blue_orange_colors[i-1]
146
+ b, (rb, gb, bb) = blue_orange_colors[i]
147
+ s = (w-a) / (b-a)
148
+ return ra+(rb-ra)*s, ga+(gb-ga)*s, ba+(bb-ba)*s
149
+
150
+ def cplot(ctx, f, re=[-5,5], im=[-5,5], points=2000, color=None,
151
+ verbose=False, file=None, dpi=None, axes=None):
152
+ """
153
+ Plots the given complex-valued function *f* over a rectangular part
154
+ of the complex plane specified by the pairs of intervals *re* and *im*.
155
+ For example::
156
+
157
+ cplot(lambda z: z, [-2, 2], [-10, 10])
158
+ cplot(exp)
159
+ cplot(zeta, [0, 1], [0, 50])
160
+
161
+ By default, the complex argument (phase) is shown as color (hue) and
162
+ the magnitude is show as brightness. You can also supply a
163
+ custom color function (*color*). This function should take a
164
+ complex number as input and return an RGB 3-tuple containing
165
+ floats in the range 0.0-1.0.
166
+
167
+ Alternatively, you can select a builtin color function by passing
168
+ a string as *color*:
169
+
170
+ * "default" - default color scheme
171
+ * "phase" - a color scheme that only renders the phase of the function,
172
+ with white for positive reals, black for negative reals, gold in the
173
+ upper half plane, and blue in the lower half plane.
174
+
175
+ To obtain a sharp image, the number of points may need to be
176
+ increased to 100,000 or thereabout. Since evaluating the
177
+ function that many times is likely to be slow, the 'verbose'
178
+ option is useful to display progress.
179
+
180
+ .. note :: This function requires matplotlib (pylab).
181
+ """
182
+ if color is None or color == "default":
183
+ color = ctx.default_color_function
184
+ if color == "phase":
185
+ color = ctx.phase_color_function
186
+ import pylab
187
+ if file:
188
+ axes = None
189
+ fig = None
190
+ if not axes:
191
+ fig = pylab.figure()
192
+ axes = fig.add_subplot(111)
193
+ rea, reb = re
194
+ ima, imb = im
195
+ dre = reb - rea
196
+ dim = imb - ima
197
+ M = int(ctx.sqrt(points*dre/dim)+1)
198
+ N = int(ctx.sqrt(points*dim/dre)+1)
199
+ x = pylab.linspace(rea, reb, M)
200
+ y = pylab.linspace(ima, imb, N)
201
+ # Note: we have to be careful to get the right rotation.
202
+ # Test with these plots:
203
+ # cplot(lambda z: z if z.real < 0 else 0)
204
+ # cplot(lambda z: z if z.imag < 0 else 0)
205
+ w = pylab.zeros((N, M, 3))
206
+ for n in xrange(N):
207
+ for m in xrange(M):
208
+ z = ctx.mpc(x[m], y[n])
209
+ try:
210
+ v = color(f(z))
211
+ except ctx.plot_ignore:
212
+ v = (0.5, 0.5, 0.5)
213
+ w[n,m] = v
214
+ if verbose:
215
+ print(str(n) + ' of ' + str(N))
216
+ rea, reb, ima, imb = [float(_) for _ in [rea, reb, ima, imb]]
217
+ axes.imshow(w, extent=(rea, reb, ima, imb), origin='lower')
218
+ axes.set_xlabel('Re(z)')
219
+ axes.set_ylabel('Im(z)')
220
+ if fig:
221
+ if file:
222
+ pylab.savefig(file, dpi=dpi)
223
+ else:
224
+ pylab.show()
225
+
226
+ def splot(ctx, f, u=[-5,5], v=[-5,5], points=100, keep_aspect=True, \
227
+ wireframe=False, file=None, dpi=None, axes=None):
228
+ """
229
+ Plots the surface defined by `f`.
230
+
231
+ If `f` returns a single component, then this plots the surface
232
+ defined by `z = f(x,y)` over the rectangular domain with
233
+ `x = u` and `y = v`.
234
+
235
+ If `f` returns three components, then this plots the parametric
236
+ surface `x, y, z = f(u,v)` over the pairs of intervals `u` and `v`.
237
+
238
+ For example, to plot a simple function::
239
+
240
+ >>> from mpmath import *
241
+ >>> f = lambda x, y: sin(x+y)*cos(y)
242
+ >>> splot(f, [-pi,pi], [-pi,pi]) # doctest: +SKIP
243
+
244
+ Plotting a donut::
245
+
246
+ >>> r, R = 1, 2.5
247
+ >>> f = lambda u, v: [r*cos(u), (R+r*sin(u))*cos(v), (R+r*sin(u))*sin(v)]
248
+ >>> splot(f, [0, 2*pi], [0, 2*pi]) # doctest: +SKIP
249
+
250
+ .. note :: This function requires matplotlib (pylab) 0.98.5.3 or higher.
251
+ """
252
+ import pylab
253
+ import mpl_toolkits.mplot3d as mplot3d
254
+ if file:
255
+ axes = None
256
+ fig = None
257
+ if not axes:
258
+ fig = pylab.figure()
259
+ axes = mplot3d.axes3d.Axes3D(fig)
260
+ ua, ub = u
261
+ va, vb = v
262
+ du = ub - ua
263
+ dv = vb - va
264
+ if not isinstance(points, (list, tuple)):
265
+ points = [points, points]
266
+ M, N = points
267
+ u = pylab.linspace(ua, ub, M)
268
+ v = pylab.linspace(va, vb, N)
269
+ x, y, z = [pylab.zeros((M, N)) for i in xrange(3)]
270
+ xab, yab, zab = [[0, 0] for i in xrange(3)]
271
+ for n in xrange(N):
272
+ for m in xrange(M):
273
+ fdata = f(ctx.convert(u[m]), ctx.convert(v[n]))
274
+ try:
275
+ x[m,n], y[m,n], z[m,n] = fdata
276
+ except TypeError:
277
+ x[m,n], y[m,n], z[m,n] = u[m], v[n], fdata
278
+ for c, cab in [(x[m,n], xab), (y[m,n], yab), (z[m,n], zab)]:
279
+ if c < cab[0]:
280
+ cab[0] = c
281
+ if c > cab[1]:
282
+ cab[1] = c
283
+ if wireframe:
284
+ axes.plot_wireframe(x, y, z, rstride=4, cstride=4)
285
+ else:
286
+ axes.plot_surface(x, y, z, rstride=4, cstride=4)
287
+ axes.set_xlabel('x')
288
+ axes.set_ylabel('y')
289
+ axes.set_zlabel('z')
290
+ if keep_aspect:
291
+ dx, dy, dz = [cab[1] - cab[0] for cab in [xab, yab, zab]]
292
+ maxd = max(dx, dy, dz)
293
+ if dx < maxd:
294
+ delta = maxd - dx
295
+ axes.set_xlim3d(xab[0] - delta / 2.0, xab[1] + delta / 2.0)
296
+ if dy < maxd:
297
+ delta = maxd - dy
298
+ axes.set_ylim3d(yab[0] - delta / 2.0, yab[1] + delta / 2.0)
299
+ if dz < maxd:
300
+ delta = maxd - dz
301
+ axes.set_zlim3d(zab[0] - delta / 2.0, zab[1] + delta / 2.0)
302
+ if fig:
303
+ if file:
304
+ pylab.savefig(file, dpi=dpi)
305
+ else:
306
+ pylab.show()
307
+
308
+
309
+ VisualizationMethods.plot = plot
310
+ VisualizationMethods.default_color_function = default_color_function
311
+ VisualizationMethods.phase_color_function = phase_color_function
312
+ VisualizationMethods.cplot = cplot
313
+ VisualizationMethods.splot = splot
env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2009, Jay Loden, Dave Daeschler, Giampaolo Rodola
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without modification,
7
+ are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the psutil authors nor the names of its contributors
17
+ may be used to endorse or promote products derived from this software without
18
+ specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
24
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
27
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/METADATA ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: psutil
3
+ Version: 5.9.8
4
+ Summary: Cross-platform lib for process and system monitoring in Python.
5
+ Home-page: https://github.com/giampaolo/psutil
6
+ Author: Giampaolo Rodola
7
+ Author-email: [email protected]
8
+ License: BSD-3-Clause
9
+ Keywords: ps,top,kill,free,lsof,netstat,nice,tty,ionice,uptime,taskmgr,process,df,iotop,iostat,ifconfig,taskset,who,pidof,pmap,smem,pstree,monitoring,ulimit,prlimit,smem,performance,metrics,agent,observability
10
+ Platform: Platform Independent
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Console
13
+ Classifier: Environment :: Win32 (MS Windows)
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Information Technology
16
+ Classifier: Intended Audience :: System Administrators
17
+ Classifier: License :: OSI Approved :: BSD License
18
+ Classifier: Operating System :: MacOS :: MacOS X
19
+ Classifier: Operating System :: Microsoft :: Windows :: Windows 10
20
+ Classifier: Operating System :: Microsoft :: Windows :: Windows 7
21
+ Classifier: Operating System :: Microsoft :: Windows :: Windows 8
22
+ Classifier: Operating System :: Microsoft :: Windows :: Windows 8.1
23
+ Classifier: Operating System :: Microsoft :: Windows :: Windows Server 2003
24
+ Classifier: Operating System :: Microsoft :: Windows :: Windows Server 2008
25
+ Classifier: Operating System :: Microsoft :: Windows :: Windows Vista
26
+ Classifier: Operating System :: Microsoft
27
+ Classifier: Operating System :: OS Independent
28
+ Classifier: Operating System :: POSIX :: AIX
29
+ Classifier: Operating System :: POSIX :: BSD :: FreeBSD
30
+ Classifier: Operating System :: POSIX :: BSD :: NetBSD
31
+ Classifier: Operating System :: POSIX :: BSD :: OpenBSD
32
+ Classifier: Operating System :: POSIX :: BSD
33
+ Classifier: Operating System :: POSIX :: Linux
34
+ Classifier: Operating System :: POSIX :: SunOS/Solaris
35
+ Classifier: Operating System :: POSIX
36
+ Classifier: Programming Language :: C
37
+ Classifier: Programming Language :: Python :: 2
38
+ Classifier: Programming Language :: Python :: 2.7
39
+ Classifier: Programming Language :: Python :: 3
40
+ Classifier: Programming Language :: Python :: Implementation :: CPython
41
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
42
+ Classifier: Programming Language :: Python
43
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
44
+ Classifier: Topic :: Software Development :: Libraries
45
+ Classifier: Topic :: System :: Benchmark
46
+ Classifier: Topic :: System :: Hardware :: Hardware Drivers
47
+ Classifier: Topic :: System :: Hardware
48
+ Classifier: Topic :: System :: Monitoring
49
+ Classifier: Topic :: System :: Networking :: Monitoring :: Hardware Watchdog
50
+ Classifier: Topic :: System :: Networking :: Monitoring
51
+ Classifier: Topic :: System :: Networking
52
+ Classifier: Topic :: System :: Operating System
53
+ Classifier: Topic :: System :: Systems Administration
54
+ Classifier: Topic :: Utilities
55
+ Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*
56
+ Description-Content-Type: text/x-rst
57
+ License-File: LICENSE
58
+ Provides-Extra: test
59
+ Requires-Dist: ipaddress ; (python_version < "3.0") and extra == 'test'
60
+ Requires-Dist: mock ; (python_version < "3.0") and extra == 'test'
61
+ Requires-Dist: enum34 ; (python_version <= "3.4") and extra == 'test'
62
+ Requires-Dist: pywin32 ; (sys_platform == "win32") and extra == 'test'
63
+ Requires-Dist: wmi ; (sys_platform == "win32") and extra == 'test'
64
+
65
+ | |downloads| |stars| |forks| |contributors| |coverage|
66
+ | |version| |py-versions| |packages| |license|
67
+ | |github-actions-wheels| |github-actions-bsd| |appveyor| |doc| |twitter| |tidelift|
68
+
69
+ .. |downloads| image:: https://img.shields.io/pypi/dm/psutil.svg
70
+ :target: https://pepy.tech/project/psutil
71
+ :alt: Downloads
72
+
73
+ .. |stars| image:: https://img.shields.io/github/stars/giampaolo/psutil.svg
74
+ :target: https://github.com/giampaolo/psutil/stargazers
75
+ :alt: Github stars
76
+
77
+ .. |forks| image:: https://img.shields.io/github/forks/giampaolo/psutil.svg
78
+ :target: https://github.com/giampaolo/psutil/network/members
79
+ :alt: Github forks
80
+
81
+ .. |contributors| image:: https://img.shields.io/github/contributors/giampaolo/psutil.svg
82
+ :target: https://github.com/giampaolo/psutil/graphs/contributors
83
+ :alt: Contributors
84
+
85
+ .. |github-actions-wheels| image:: https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/build.yml?label=Linux%2C%20macOS%2C%20Windows
86
+ :target: https://github.com/giampaolo/psutil/actions?query=workflow%3Abuild
87
+ :alt: Linux, macOS, Windows
88
+
89
+ .. |github-actions-bsd| image:: https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/bsd.yml?label=FreeBSD,%20NetBSD,%20OpenBSD
90
+ :target: https://github.com/giampaolo/psutil/actions?query=workflow%3Absd-tests
91
+ :alt: FreeBSD, NetBSD, OpenBSD
92
+
93
+ .. |appveyor| image:: https://img.shields.io/appveyor/build/giampaolo/psutil/master.svg?maxAge=3600&label=Windows%20(py2)
94
+ :target: https://ci.appveyor.com/project/giampaolo/psutil
95
+ :alt: Windows (Appveyor)
96
+
97
+ .. |coverage| image:: https://coveralls.io/repos/github/giampaolo/psutil/badge.svg?branch=master
98
+ :target: https://coveralls.io/github/giampaolo/psutil?branch=master
99
+ :alt: Test coverage (coverall.io)
100
+
101
+ .. |doc| image:: https://readthedocs.org/projects/psutil/badge/?version=latest
102
+ :target: https://psutil.readthedocs.io/en/latest/
103
+ :alt: Documentation Status
104
+
105
+ .. |version| image:: https://img.shields.io/pypi/v/psutil.svg?label=pypi
106
+ :target: https://pypi.org/project/psutil
107
+ :alt: Latest version
108
+
109
+ .. |py-versions| image:: https://img.shields.io/pypi/pyversions/psutil.svg
110
+ :alt: Supported Python versions
111
+
112
+ .. |packages| image:: https://repology.org/badge/tiny-repos/python:psutil.svg
113
+ :target: https://repology.org/metapackage/python:psutil/versions
114
+ :alt: Binary packages
115
+
116
+ .. |license| image:: https://img.shields.io/pypi/l/psutil.svg
117
+ :target: https://github.com/giampaolo/psutil/blob/master/LICENSE
118
+ :alt: License
119
+
120
+ .. |twitter| image:: https://img.shields.io/twitter/follow/grodola.svg?label=follow&style=flat&logo=twitter&logoColor=4FADFF
121
+ :target: https://twitter.com/grodola
122
+ :alt: Twitter Follow
123
+
124
+ .. |tidelift| image:: https://tidelift.com/badges/github/giampaolo/psutil?style=flat
125
+ :target: https://tidelift.com/subscription/pkg/pypi-psutil?utm_source=pypi-psutil&utm_medium=referral&utm_campaign=readme
126
+ :alt: Tidelift
127
+
128
+ -----
129
+
130
+ Quick links
131
+ ===========
132
+
133
+ - `Home page <https://github.com/giampaolo/psutil>`_
134
+ - `Install <https://github.com/giampaolo/psutil/blob/master/INSTALL.rst>`_
135
+ - `Documentation <http://psutil.readthedocs.io>`_
136
+ - `Download <https://pypi.org/project/psutil/#files>`_
137
+ - `Forum <http://groups.google.com/group/psutil/topics>`_
138
+ - `StackOverflow <https://stackoverflow.com/questions/tagged/psutil>`_
139
+ - `Blog <https://gmpy.dev/tags/psutil>`_
140
+ - `What's new <https://github.com/giampaolo/psutil/blob/master/HISTORY.rst>`_
141
+
142
+
143
+ Summary
144
+ =======
145
+
146
+ psutil (process and system utilities) is a cross-platform library for
147
+ retrieving information on **running processes** and **system utilization**
148
+ (CPU, memory, disks, network, sensors) in Python.
149
+ It is useful mainly for **system monitoring**, **profiling and limiting process
150
+ resources** and **management of running processes**.
151
+ It implements many functionalities offered by classic UNIX command line tools
152
+ such as *ps, top, iotop, lsof, netstat, ifconfig, free* and others.
153
+ psutil currently supports the following platforms:
154
+
155
+ - **Linux**
156
+ - **Windows**
157
+ - **macOS**
158
+ - **FreeBSD, OpenBSD**, **NetBSD**
159
+ - **Sun Solaris**
160
+ - **AIX**
161
+
162
+ Supported Python versions are **2.7**, **3.6+** and
163
+ `PyPy <http://pypy.org/>`__.
164
+
165
+ Funding
166
+ =======
167
+
168
+ While psutil is free software and will always be, the project would benefit
169
+ immensely from some funding.
170
+ Keeping up with bug reports and maintenance has become hardly sustainable for
171
+ me alone in terms of time.
172
+ If you're a company that's making significant use of psutil you can consider
173
+ becoming a sponsor via `GitHub Sponsors <https://github.com/sponsors/giampaolo>`__,
174
+ `Open Collective <https://opencollective.com/psutil>`__ or
175
+ `PayPal <https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=A9ZS7PKKRM3S8>`__
176
+ and have your logo displayed in here and psutil `doc <https://psutil.readthedocs.io>`__.
177
+
178
+ Sponsors
179
+ ========
180
+
181
+ .. image:: https://github.com/giampaolo/psutil/raw/master/docs/_static/tidelift-logo.png
182
+ :width: 200
183
+ :alt: Alternative text
184
+
185
+ `Add your logo <https://github.com/sponsors/giampaolo>`__.
186
+
187
+ Example usages
188
+ ==============
189
+
190
+ This represents pretty much the whole psutil API.
191
+
192
+ CPU
193
+ ---
194
+
195
+ .. code-block:: python
196
+
197
+ >>> import psutil
198
+ >>>
199
+ >>> psutil.cpu_times()
200
+ scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, guest_nice=0.0)
201
+ >>>
202
+ >>> for x in range(3):
203
+ ... psutil.cpu_percent(interval=1)
204
+ ...
205
+ 4.0
206
+ 5.9
207
+ 3.8
208
+ >>>
209
+ >>> for x in range(3):
210
+ ... psutil.cpu_percent(interval=1, percpu=True)
211
+ ...
212
+ [4.0, 6.9, 3.7, 9.2]
213
+ [7.0, 8.5, 2.4, 2.1]
214
+ [1.2, 9.0, 9.9, 7.2]
215
+ >>>
216
+ >>> for x in range(3):
217
+ ... psutil.cpu_times_percent(interval=1, percpu=False)
218
+ ...
219
+ scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
220
+ scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
221
+ scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
222
+ >>>
223
+ >>> psutil.cpu_count()
224
+ 4
225
+ >>> psutil.cpu_count(logical=False)
226
+ 2
227
+ >>>
228
+ >>> psutil.cpu_stats()
229
+ scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0)
230
+ >>>
231
+ >>> psutil.cpu_freq()
232
+ scpufreq(current=931.42925, min=800.0, max=3500.0)
233
+ >>>
234
+ >>> psutil.getloadavg() # also on Windows (emulated)
235
+ (3.14, 3.89, 4.67)
236
+
237
+ Memory
238
+ ------
239
+
240
+ .. code-block:: python
241
+
242
+ >>> psutil.virtual_memory()
243
+ svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304)
244
+ >>> psutil.swap_memory()
245
+ sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944)
246
+ >>>
247
+
248
+ Disks
249
+ -----
250
+
251
+ .. code-block:: python
252
+
253
+ >>> psutil.disk_partitions()
254
+ [sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid', maxfile=255, maxpath=4096),
255
+ sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext', opts='rw', maxfile=255, maxpath=4096)]
256
+ >>>
257
+ >>> psutil.disk_usage('/')
258
+ sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
259
+ >>>
260
+ >>> psutil.disk_io_counters(perdisk=False)
261
+ sdiskio(read_count=719566, write_count=1082197, read_bytes=18626220032, write_bytes=24081764352, read_time=5023392, write_time=63199568, read_merged_count=619166, write_merged_count=812396, busy_time=4523412)
262
+ >>>
263
+
264
+ Network
265
+ -------
266
+
267
+ .. code-block:: python
268
+
269
+ >>> psutil.net_io_counters(pernic=True)
270
+ {'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0),
271
+ 'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)}
272
+ >>>
273
+ >>> psutil.net_connections(kind='tcp')
274
+ [sconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254),
275
+ sconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987),
276
+ ...]
277
+ >>>
278
+ >>> psutil.net_if_addrs()
279
+ {'lo': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
280
+ snicaddr(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
281
+ snicaddr(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
282
+ 'wlan0': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
283
+ snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
284
+ snicaddr(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
285
+ >>>
286
+ >>> psutil.net_if_stats()
287
+ {'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=65536, flags='up,loopback,running'),
288
+ 'wlan0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500, flags='up,broadcast,running,multicast')}
289
+ >>>
290
+
291
+ Sensors
292
+ -------
293
+
294
+ .. code-block:: python
295
+
296
+ >>> import psutil
297
+ >>> psutil.sensors_temperatures()
298
+ {'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)],
299
+ 'asus': [shwtemp(label='', current=47.0, high=None, critical=None)],
300
+ 'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0),
301
+ shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0)]}
302
+ >>>
303
+ >>> psutil.sensors_fans()
304
+ {'asus': [sfan(label='cpu_fan', current=3200)]}
305
+ >>>
306
+ >>> psutil.sensors_battery()
307
+ sbattery(percent=93, secsleft=16628, power_plugged=False)
308
+ >>>
309
+
310
+ Other system info
311
+ -----------------
312
+
313
+ .. code-block:: python
314
+
315
+ >>> import psutil
316
+ >>> psutil.users()
317
+ [suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352),
318
+ suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)]
319
+ >>>
320
+ >>> psutil.boot_time()
321
+ 1365519115.0
322
+ >>>
323
+
324
+ Process management
325
+ ------------------
326
+
327
+ .. code-block:: python
328
+
329
+ >>> import psutil
330
+ >>> psutil.pids()
331
+ [1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215,
332
+ 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355, 2637, 2774, 3932,
333
+ 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 4263, 4282, 4306, 4311,
334
+ 4312, 4313, 4314, 4337, 4339, 4357, 4358, 4363, 4383, 4395, 4408, 4433,
335
+ 4443, 4445, 4446, 5167, 5234, 5235, 5252, 5318, 5424, 5644, 6987, 7054,
336
+ 7055, 7071]
337
+ >>>
338
+ >>> p = psutil.Process(7055)
339
+ >>> p
340
+ psutil.Process(pid=7055, name='python3', status='running', started='09:04:44')
341
+ >>> p.pid
342
+ 7055
343
+ >>> p.name()
344
+ 'python3'
345
+ >>> p.exe()
346
+ '/usr/bin/python3'
347
+ >>> p.cwd()
348
+ '/home/giampaolo'
349
+ >>> p.cmdline()
350
+ ['/usr/bin/python3', 'main.py']
351
+ >>>
352
+ >>> p.ppid()
353
+ 7054
354
+ >>> p.parent()
355
+ psutil.Process(pid=4699, name='bash', status='sleeping', started='09:06:44')
356
+ >>> p.parents()
357
+ [psutil.Process(pid=4699, name='bash', started='09:06:44'),
358
+ psutil.Process(pid=4689, name='gnome-terminal-server', status='sleeping', started='0:06:44'),
359
+ psutil.Process(pid=1, name='systemd', status='sleeping', started='05:56:55')]
360
+ >>> p.children(recursive=True)
361
+ [psutil.Process(pid=29835, name='python3', status='sleeping', started='11:45:38'),
362
+ psutil.Process(pid=29836, name='python3', status='waking', started='11:43:39')]
363
+ >>>
364
+ >>> p.status()
365
+ 'running'
366
+ >>> p.create_time()
367
+ 1267551141.5019531
368
+ >>> p.terminal()
369
+ '/dev/pts/0'
370
+ >>>
371
+ >>> p.username()
372
+ 'giampaolo'
373
+ >>> p.uids()
374
+ puids(real=1000, effective=1000, saved=1000)
375
+ >>> p.gids()
376
+ pgids(real=1000, effective=1000, saved=1000)
377
+ >>>
378
+ >>> p.cpu_times()
379
+ pcputimes(user=1.02, system=0.31, children_user=0.32, children_system=0.1, iowait=0.0)
380
+ >>> p.cpu_percent(interval=1.0)
381
+ 12.1
382
+ >>> p.cpu_affinity()
383
+ [0, 1, 2, 3]
384
+ >>> p.cpu_affinity([0, 1]) # set
385
+ >>> p.cpu_num()
386
+ 1
387
+ >>>
388
+ >>> p.memory_info()
389
+ pmem(rss=10915840, vms=67608576, shared=3313664, text=2310144, lib=0, data=7262208, dirty=0)
390
+ >>> p.memory_full_info() # "real" USS memory usage (Linux, macOS, Win only)
391
+ pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0)
392
+ >>> p.memory_percent()
393
+ 0.7823
394
+ >>> p.memory_maps()
395
+ [pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0),
396
+ pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=3821568, size=3842048, pss=3821568, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=3821568, referenced=3575808, anonymous=3821568, swap=0),
397
+ pmmap_grouped(path='[heap]', rss=32768, size=139264, pss=32768, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=32768, referenced=32768, anonymous=32768, swap=0),
398
+ pmmap_grouped(path='[stack]', rss=2465792, size=2494464, pss=2465792, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=2465792, referenced=2277376, anonymous=2465792, swap=0),
399
+ ...]
400
+ >>>
401
+ >>> p.io_counters()
402
+ pio(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632, read_chars=456232, write_chars=517543)
403
+ >>>
404
+ >>> p.open_files()
405
+ [popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768),
406
+ popenfile(path='/var/log/monit.log', fd=4, position=235542, mode='a', flags=33793)]
407
+ >>>
408
+ >>> p.connections(kind='tcp')
409
+ [pconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED'),
410
+ pconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING')]
411
+ >>>
412
+ >>> p.threads()
413
+ [pthread(id=5234, user_time=22.5, system_time=9.2891),
414
+ pthread(id=5237, user_time=0.0707, system_time=1.1)]
415
+ >>>
416
+ >>> p.num_threads()
417
+ 4
418
+ >>> p.num_fds()
419
+ 8
420
+ >>> p.num_ctx_switches()
421
+ pctxsw(voluntary=78, involuntary=19)
422
+ >>>
423
+ >>> p.nice()
424
+ 0
425
+ >>> p.nice(10) # set
426
+ >>>
427
+ >>> p.ionice(psutil.IOPRIO_CLASS_IDLE) # IO priority (Win and Linux only)
428
+ >>> p.ionice()
429
+ pionice(ioclass=<IOPriority.IOPRIO_CLASS_IDLE: 3>, value=0)
430
+ >>>
431
+ >>> p.rlimit(psutil.RLIMIT_NOFILE, (5, 5)) # set resource limits (Linux only)
432
+ >>> p.rlimit(psutil.RLIMIT_NOFILE)
433
+ (5, 5)
434
+ >>>
435
+ >>> p.environ()
436
+ {'LC_PAPER': 'it_IT.UTF-8', 'SHELL': '/bin/bash', 'GREP_OPTIONS': '--color=auto',
437
+ 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg',
438
+ ...}
439
+ >>>
440
+ >>> p.as_dict()
441
+ {'status': 'running', 'num_ctx_switches': pctxsw(voluntary=63, involuntary=1), 'pid': 5457, ...}
442
+ >>> p.is_running()
443
+ True
444
+ >>> p.suspend()
445
+ >>> p.resume()
446
+ >>>
447
+ >>> p.terminate()
448
+ >>> p.kill()
449
+ >>> p.wait(timeout=3)
450
+ <Exitcode.EX_OK: 0>
451
+ >>>
452
+ >>> psutil.test()
453
+ USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND
454
+ root 1 0.0 0.0 24584 2240 Jun17 00:00 init
455
+ root 2 0.0 0.0 0 0 Jun17 00:00 kthreadd
456
+ ...
457
+ giampaolo 31475 0.0 0.0 20760 3024 /dev/pts/0 Jun19 00:00 python2.4
458
+ giampaolo 31721 0.0 2.2 773060 181896 00:04 10:30 chrome
459
+ root 31763 0.0 0.0 0 0 00:05 00:00 kworker/0:1
460
+ >>>
461
+
462
+ Further process APIs
463
+ --------------------
464
+
465
+ .. code-block:: python
466
+
467
+ >>> import psutil
468
+ >>> for proc in psutil.process_iter(['pid', 'name']):
469
+ ... print(proc.info)
470
+ ...
471
+ {'pid': 1, 'name': 'systemd'}
472
+ {'pid': 2, 'name': 'kthreadd'}
473
+ {'pid': 3, 'name': 'ksoftirqd/0'}
474
+ ...
475
+ >>>
476
+ >>> psutil.pid_exists(3)
477
+ True
478
+ >>>
479
+ >>> def on_terminate(proc):
480
+ ... print("process {} terminated".format(proc))
481
+ ...
482
+ >>> # waits for multiple processes to terminate
483
+ >>> gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate)
484
+ >>>
485
+
486
+ Windows services
487
+ ----------------
488
+
489
+ .. code-block:: python
490
+
491
+ >>> list(psutil.win_service_iter())
492
+ [<WindowsService(name='AeLookupSvc', display_name='Application Experience') at 38850096>,
493
+ <WindowsService(name='ALG', display_name='Application Layer Gateway Service') at 38850128>,
494
+ <WindowsService(name='APNMCP', display_name='Ask Update Service') at 38850160>,
495
+ <WindowsService(name='AppIDSvc', display_name='Application Identity') at 38850192>,
496
+ ...]
497
+ >>> s = psutil.win_service_get('alg')
498
+ >>> s.as_dict()
499
+ {'binpath': 'C:\\Windows\\System32\\alg.exe',
500
+ 'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing',
501
+ 'display_name': 'Application Layer Gateway Service',
502
+ 'name': 'alg',
503
+ 'pid': None,
504
+ 'start_type': 'manual',
505
+ 'status': 'stopped',
506
+ 'username': 'NT AUTHORITY\\LocalService'}
507
+
508
+ Projects using psutil
509
+ =====================
510
+
511
+ Here's some I find particularly interesting:
512
+
513
+ - https://github.com/google/grr
514
+ - https://github.com/facebook/osquery/
515
+ - https://github.com/nicolargo/glances
516
+ - https://github.com/aristocratos/bpytop
517
+ - https://github.com/Jahaja/psdash
518
+ - https://github.com/ajenti/ajenti
519
+ - https://github.com/home-assistant/home-assistant/
520
+
521
+ Portings
522
+ ========
523
+
524
+ - Go: https://github.com/shirou/gopsutil
525
+ - C: https://github.com/hamon-in/cpslib
526
+ - Rust: https://github.com/rust-psutil/rust-psutil
527
+ - Nim: https://github.com/johnscillieri/psutil-nim
528
+
529
+
530
+
env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/RECORD ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ psutil-5.9.8.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ psutil-5.9.8.dist-info/LICENSE,sha256=uJwGOzeG4o4MCjjxkx22H-015p3SopZvvs_-4PRsjRA,1548
3
+ psutil-5.9.8.dist-info/METADATA,sha256=GfZ5-fidrq0yXOCgyN4funClVHk6R_zfJz-3FKx0KjU,21837
4
+ psutil-5.9.8.dist-info/RECORD,,
5
+ psutil-5.9.8.dist-info/WHEEL,sha256=rgpVBmjjvbINeGKCkWEGd3f40VHMTsDkQj1Lgil82zE,221
6
+ psutil-5.9.8.dist-info/top_level.txt,sha256=gCNhn57wzksDjSAISmgMJ0aiXzQulk0GJhb2-BAyYgw,7
7
+ psutil/__init__.py,sha256=YWf_i2ZjuJqELRfNl6nX0nZuoi09GXqMZPJVsMJMCQQ,89169
8
+ psutil/__pycache__/__init__.cpython-310.pyc,,
9
+ psutil/__pycache__/_common.cpython-310.pyc,,
10
+ psutil/__pycache__/_compat.cpython-310.pyc,,
11
+ psutil/__pycache__/_psaix.cpython-310.pyc,,
12
+ psutil/__pycache__/_psbsd.cpython-310.pyc,,
13
+ psutil/__pycache__/_pslinux.cpython-310.pyc,,
14
+ psutil/__pycache__/_psosx.cpython-310.pyc,,
15
+ psutil/__pycache__/_psposix.cpython-310.pyc,,
16
+ psutil/__pycache__/_pssunos.cpython-310.pyc,,
17
+ psutil/__pycache__/_pswindows.cpython-310.pyc,,
18
+ psutil/_common.py,sha256=BTwHxdYJQynrn5i8IOs6XFxLo9L1Eg5cgDCq6Yaypr0,29393
19
+ psutil/_compat.py,sha256=AOF0vSCWle_sbJ1Gw-CGx0aEI9yk5u70YhPYOPg3KHs,15349
20
+ psutil/_psaix.py,sha256=1bqEwjk6IG3Y-zrDajKi8oPSYvq3NrqpPUQeDRo4Ugg,18749
21
+ psutil/_psbsd.py,sha256=FruAJy_GrpjAfHLpb4c3IVGfy2Xii8b1BHnIjxUfbbI,31956
22
+ psutil/_pslinux.py,sha256=QYI6yHTvRMYZlVxB068xVAEMEAGGRSU9E7-sJD3165o,88043
23
+ psutil/_psosx.py,sha256=d_KMSzmjL6vAYQx1fQN57b3xazJGdTt4rIysODB1r2g,16209
24
+ psutil/_psposix.py,sha256=X9rd7WHKQ6mUAn2ihb03MCnzrBtQsrPRkCouExmuagQ,8235
25
+ psutil/_pssunos.py,sha256=Zx6eLY-0NRUFFIKP7SycktgDoottdnlA9aX8y4e74dY,25559
26
+ psutil/_psutil_linux.abi3.so,sha256=onwm8BWn6axbKjPqB263JHm6rbDcEvMncKYhhpbu5I4,115304
27
+ psutil/_psutil_posix.abi3.so,sha256=xNVKy1LdKcnigEe_BpaXfYEg4qad9MkedLwkYh4BaBk,71624
28
+ psutil/_pswindows.py,sha256=BXgoASpIS6ccw5jTx4V-H2fMsIcSv_NQ6EozsxFgY-0,37734
29
+ psutil/tests/__init__.py,sha256=gc621Vvgj2NaxusB_zGwfqwP_np3qaCQqJlyPrp1D0k,64753
30
+ psutil/tests/__main__.py,sha256=f1YY6SZebctd5Hwb1in40nFShfJw4zA2FLidsdg_eY8,269
31
+ psutil/tests/__pycache__/__init__.cpython-310.pyc,,
32
+ psutil/tests/__pycache__/__main__.cpython-310.pyc,,
33
+ psutil/tests/__pycache__/runner.cpython-310.pyc,,
34
+ psutil/tests/__pycache__/test_aix.cpython-310.pyc,,
35
+ psutil/tests/__pycache__/test_bsd.cpython-310.pyc,,
36
+ psutil/tests/__pycache__/test_connections.cpython-310.pyc,,
37
+ psutil/tests/__pycache__/test_contracts.cpython-310.pyc,,
38
+ psutil/tests/__pycache__/test_linux.cpython-310.pyc,,
39
+ psutil/tests/__pycache__/test_memleaks.cpython-310.pyc,,
40
+ psutil/tests/__pycache__/test_misc.cpython-310.pyc,,
41
+ psutil/tests/__pycache__/test_osx.cpython-310.pyc,,
42
+ psutil/tests/__pycache__/test_posix.cpython-310.pyc,,
43
+ psutil/tests/__pycache__/test_process.cpython-310.pyc,,
44
+ psutil/tests/__pycache__/test_process_all.cpython-310.pyc,,
45
+ psutil/tests/__pycache__/test_sunos.cpython-310.pyc,,
46
+ psutil/tests/__pycache__/test_system.cpython-310.pyc,,
47
+ psutil/tests/__pycache__/test_testutils.cpython-310.pyc,,
48
+ psutil/tests/__pycache__/test_unicode.cpython-310.pyc,,
49
+ psutil/tests/__pycache__/test_windows.cpython-310.pyc,,
50
+ psutil/tests/runner.py,sha256=WtRnLZ5gS39gIysLCkeV99hw5LvodVwBGesoen9IMNs,11464
51
+ psutil/tests/test_aix.py,sha256=8SKjFw7cR3byBShlvWAzQSOTjji5Bpnk8JyUksR0AQI,4585
52
+ psutil/tests/test_bsd.py,sha256=kfNXLsZ1p-VoGtVX4At9qMOS_zN8OMVP9yecuHEWaC4,21245
53
+ psutil/tests/test_connections.py,sha256=CHL65q2IYxb8ErtJAUh87RyKSCWewwmAg4VFK80arO8,21642
54
+ psutil/tests/test_contracts.py,sha256=_TAWN7ldbgqJIdh6tMkRDivXPoH6T3jKYG47_KzDvtE,12998
55
+ psutil/tests/test_linux.py,sha256=LPvhEPUPSQ4MdxBlARPcR4Thsd_wNqKkqj0JqlKkZCo,92530
56
+ psutil/tests/test_memleaks.py,sha256=pzwEMUaz6Xh8AmN_qiCmYTU2yzot_dwsdbTfFdK89Vk,15012
57
+ psutil/tests/test_misc.py,sha256=JovYMJNShu2yC3t2sfkFY5uW96TL7K5gkwXnjOR25aQ,35117
58
+ psutil/tests/test_osx.py,sha256=MQsepO25TlfydaOxjqgEBM4Wri9SnCUkpBLEiQnKv2Q,6603
59
+ psutil/tests/test_posix.py,sha256=sDam9vdJJWuYNddovhxi1c3K-z4AfTAD0fQyyaeD8YY,17387
60
+ psutil/tests/test_process.py,sha256=lOq3nOyQQvKRJRaTREO0GB0ErOQGZeqxHsEbn5qs8P4,61535
61
+ psutil/tests/test_process_all.py,sha256=qkLXnkVVYEqM2IhhID0CzEVWAmD4Ib7i0E4mUjo8J_Y,16112
62
+ psutil/tests/test_sunos.py,sha256=NhZsHABJKjCEDzGA7ZL62s6NlqpJwpoDybaPB2Bm9HE,1310
63
+ psutil/tests/test_system.py,sha256=rfzGP_ZuMHxzuTz3CuVxn8-zXNe5_9YCm1Z5JTKXqT8,37044
64
+ psutil/tests/test_testutils.py,sha256=mBbsRBbUf4VmDrKTbvlSeVqo_5HTM9h4eTE_VZ_5eXc,14828
65
+ psutil/tests/test_unicode.py,sha256=lKytzxNA72Zdhhz6jnXjVRm-3-79j1zeliPO1SMSVaE,12549
66
+ psutil/tests/test_windows.py,sha256=D_fKdhp8rsXDF7OrBXLRPS7XMpqXAzqJzbrjPqlL5pE,35298
env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/WHEEL ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp36-abi3-manylinux_2_12_x86_64
5
+ Tag: cp36-abi3-manylinux2010_x86_64
6
+ Tag: cp36-abi3-manylinux_2_17_x86_64
7
+ Tag: cp36-abi3-manylinux2014_x86_64
8
+
env-llmeval/lib/python3.10/site-packages/psutil-5.9.8.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ psutil
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_cell.cpython-310.pyc ADDED
Binary file (884 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_font.cpython-310.pyc ADDED
Binary file (887 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_style.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler_interface.cpython-310.pyc ADDED
Binary file (1.38 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_theme.cpython-310.pyc ADDED
Binary file (3.49 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/_cell.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Any
3
+
4
+ from ._style import Style
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Cell:
9
+ """
10
+ A data class representing a cell in a table.
11
+ """
12
+
13
+ row: int
14
+ """row index. ``-1`` means that the table header row."""
15
+
16
+ col: int
17
+ """column index."""
18
+
19
+ value: Any
20
+ """data for the cell."""
21
+
22
+ default_style: Style
23
+ """default |Style| for the cell."""
24
+
25
+ def is_header_row(self) -> bool:
26
+ """
27
+ Return |True| if the cell is a header.
28
+ """
29
+
30
+ return self.row < 0
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/_style.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from enum import Enum, unique
3
+ from typing import Any, Dict, Optional, Union
4
+
5
+ from dataproperty import Align
6
+ from tcolorpy import Color
7
+
8
+ from .._function import normalize_enum
9
+ from ._font import FontSize, FontStyle, FontWeight
10
+
11
+
12
+ @unique
13
+ class DecorationLine(Enum):
14
+ NONE = "none"
15
+ LINE_THROUGH = "line_through"
16
+ STRIKE = "strike"
17
+ UNDERLINE = "underline"
18
+
19
+
20
+ @unique
21
+ class ThousandSeparator(Enum):
22
+ NONE = "none" #: no thousands separator
23
+ COMMA = "comma" #: ``','`` as thousands separator
24
+ SPACE = "space" #: ``' '`` as thousands separator
25
+ UNDERSCORE = "underscore" #: ``'_'`` as thousands separator
26
+
27
+
28
+ @unique
29
+ class VerticalAlign(Enum):
30
+ BASELINE = (1 << 0, "baseline")
31
+ TOP = (1 << 1, "top")
32
+ MIDDLE = (1 << 2, "middle")
33
+ BOTTOM = (1 << 3, "bottom")
34
+
35
+ @property
36
+ def align_code(self) -> int:
37
+ return self.__align_code
38
+
39
+ @property
40
+ def align_str(self) -> str:
41
+ return self.__align_string
42
+
43
+ def __init__(self, code: int, string: str) -> None:
44
+ self.__align_code = code
45
+ self.__align_string = string
46
+
47
+
48
+ _s_to_ts: Dict[str, ThousandSeparator] = {
49
+ "": ThousandSeparator.NONE,
50
+ ",": ThousandSeparator.COMMA,
51
+ " ": ThousandSeparator.SPACE,
52
+ "_": ThousandSeparator.UNDERSCORE,
53
+ }
54
+
55
+
56
+ def _normalize_thousand_separator(value: Union[str, ThousandSeparator]) -> ThousandSeparator:
57
+ if isinstance(value, ThousandSeparator):
58
+ return value
59
+
60
+ thousand_separator = normalize_enum(
61
+ value,
62
+ ThousandSeparator,
63
+ default=ThousandSeparator.NONE,
64
+ validate=False,
65
+ )
66
+ if isinstance(thousand_separator, ThousandSeparator):
67
+ return thousand_separator
68
+
69
+ norm_value = _s_to_ts.get(value)
70
+ if norm_value is None:
71
+ raise ValueError(f"unknown thousand separator: {value}")
72
+
73
+ return norm_value
74
+
75
+
76
+ class Style:
77
+ """Style specifier class for table elements.
78
+
79
+ Args:
80
+ color (Union[|str|, tcolorpy.Color, |None|]):
81
+ Text color for cells.
82
+ When using str, specify a color code (``"#XXXXXX"``) or a color name.
83
+
84
+ .. note::
85
+ In the current version, only applicable for part of text format writer classes.
86
+
87
+ fg_color (Union[|str|, tcolorpy.Color, |None|]):
88
+ Alias to :py:attr:`~.color`.
89
+
90
+ bg_color (Union[|str|, tcolorpy.Color, |None|]):
91
+ Background color for cells.
92
+ When using str, specify a color code (``"#XXXXXX"``) or a color name.
93
+
94
+ .. note::
95
+ In the current version, only applicable for part of text format writer classes.
96
+
97
+ align (|str| / :py:class:`~.style.Align`):
98
+ Horizontal text alignment for cells.
99
+ This can be only applied for text format writer classes.
100
+ Possible string values are:
101
+
102
+ - ``"auto"`` (default)
103
+ - Detect data type for each column and set alignment that appropriate
104
+ for the type automatically
105
+ - ``"left"``
106
+ - ``"right"``
107
+ - ``"center"``
108
+
109
+ vertical_align (|str| / :py:class:`~.style.VerticalAlign`):
110
+ Vertical text alignment for cells.
111
+ This can be only applied for HtmlTableWriter class.
112
+ Possible string values are:
113
+
114
+ - ``"baseline"`` (default)
115
+ - ``"top"``
116
+ - ``"middle"``
117
+ - ``"bottom"``
118
+
119
+ font_size (|str| / :py:class:`~.style.FontSize`):
120
+ Font size specification for cells in a column.
121
+ This can be only applied for HTML/Latex writer classes.
122
+ Possible string values are:
123
+
124
+ - ``"tiny"``
125
+ - ``"small"``
126
+ - ``"medium"``
127
+ - ``"large"``
128
+ - ``"none"`` (default: no font size specification)
129
+
130
+ font_weight (|str| / :py:class:`~.style.FontWeight`):
131
+ Font weight specification for cells in a column.
132
+ This can be only applied for HTML/Latex/Markdown writer classes.
133
+ Possible string values are:
134
+
135
+ - ``"normal"`` (default)
136
+ - ``"bold"``
137
+
138
+ font_style (|str| / :py:class:`~.style.FontStyle`):
139
+ Font style specification for cells in a column.
140
+ This can be applied only for HTML/Latex/Markdown writer classes.
141
+ Possible string values are:
142
+
143
+ - ``"normal"`` (default)
144
+ - ``"italic"``
145
+ - ``"typewriter"`` (only for Latex writer)
146
+
147
+ decoration_line (|str| / :py:class:`~.style.DecorationLine`)
148
+
149
+ Experiental.
150
+ Possible string values are:
151
+
152
+ - ``"line-through"``
153
+ - ``"strike"`` (alias for ``"line-through"``)
154
+ - ``"underline"``
155
+ - ``"none"`` (default)
156
+
157
+ thousand_separator (|str| / :py:class:`~.style.ThousandSeparator`):
158
+ Thousand separator specification for numbers in a column.
159
+ This can be only applied for text format writer classes.
160
+ Possible string values are:
161
+
162
+ - ``","``/``"comma"``
163
+ - ``" "``/``"space"``
164
+ - ``"_"``/``"underscore"``
165
+ - ``""``/``"none"`` (default)
166
+
167
+ Example:
168
+ :ref:`example-style`
169
+ """
170
+
171
+ @property
172
+ def align(self) -> Align:
173
+ return self.__align
174
+
175
+ @align.setter
176
+ def align(self, value: Align) -> None:
177
+ self.__align = value
178
+
179
+ @property
180
+ def vertical_align(self) -> VerticalAlign:
181
+ return self.__valign
182
+
183
+ @property
184
+ def decoration_line(self) -> DecorationLine:
185
+ return self.__decoration_line
186
+
187
+ @property
188
+ def font_size(self) -> FontSize:
189
+ return self.__font_size
190
+
191
+ @property
192
+ def font_style(self) -> FontStyle:
193
+ return self.__font_style
194
+
195
+ @property
196
+ def font_weight(self) -> FontWeight:
197
+ return self.__font_weight
198
+
199
+ @property
200
+ def color(self) -> Optional[Color]:
201
+ return self.__fg_color
202
+
203
+ @property
204
+ def fg_color(self) -> Optional[Color]:
205
+ return self.__fg_color
206
+
207
+ @property
208
+ def bg_color(self) -> Optional[Color]:
209
+ return self.__bg_color
210
+
211
+ @property
212
+ def thousand_separator(self) -> ThousandSeparator:
213
+ return self.__thousand_separator
214
+
215
+ @property
216
+ def padding(self) -> Optional[int]:
217
+ return self.__padding
218
+
219
+ @padding.setter
220
+ def padding(self, value: Optional[int]) -> None:
221
+ self.__padding = value
222
+
223
+ def __init__(self, **kwargs: Any) -> None:
224
+ self.__kwargs = kwargs
225
+ self.__update_color(initialize=True)
226
+ self.__update_align(initialize=True)
227
+ self.__update_font(initialize=True)
228
+ self.__update_misc(initialize=True)
229
+
230
+ if self.__kwargs:
231
+ warnings.warn(f"unknown style attributes found: {self.__kwargs.keys()}", UserWarning)
232
+
233
+ def __repr__(self) -> str:
234
+ items = []
235
+
236
+ if self.align:
237
+ items.append(f"align={self.align.align_string}")
238
+ if self.padding is not None:
239
+ items.append(f"padding={self.padding}")
240
+ if self.vertical_align:
241
+ items.append(f"valign={self.vertical_align.align_str}")
242
+ if self.color:
243
+ items.append(f"color={self.color}")
244
+ if self.bg_color:
245
+ items.append(f"bg_color={self.bg_color}")
246
+ if self.decoration_line is not DecorationLine.NONE:
247
+ items.append(f"decoration_line={self.decoration_line.value}")
248
+ if self.font_size is not FontSize.NONE:
249
+ items.append(f"font_size={self.font_size.value}")
250
+ if self.font_style:
251
+ items.append(f"font_style={self.font_style.value}")
252
+ if self.font_weight:
253
+ items.append(f"font_weight={self.font_weight.value}")
254
+ if self.thousand_separator is not ThousandSeparator.NONE:
255
+ items.append(f"thousand_separator={self.thousand_separator.value}")
256
+
257
+ return "({})".format(", ".join(items))
258
+
259
+ def __eq__(self, other: Any) -> bool:
260
+ if self.__class__ is not other.__class__:
261
+ return False
262
+
263
+ return all(
264
+ [
265
+ self.align == other.align,
266
+ self.font_size == other.font_size,
267
+ self.font_style == other.font_style,
268
+ self.font_weight == other.font_weight,
269
+ self.thousand_separator == other.thousand_separator,
270
+ ]
271
+ )
272
+
273
+ def __ne__(self, other: Any) -> bool:
274
+ if self.__class__ is not other.__class__:
275
+ return True
276
+
277
+ return not self.__eq__(other)
278
+
279
+ def update(self, **kwargs: Any) -> None:
280
+ """Update specified style attributes."""
281
+ self.__kwargs = kwargs
282
+ self.__update_color(initialize=False)
283
+ self.__update_align(initialize=False)
284
+ self.__update_font(initialize=False)
285
+ self.__update_misc(initialize=False)
286
+
287
+ if self.__kwargs:
288
+ warnings.warn(f"unknown style attributes found: {self.__kwargs.keys()}", UserWarning)
289
+
290
+ def __update_color(self, initialize: bool) -> None:
291
+ fg_color = self.__kwargs.pop("color", None) or self.__kwargs.pop("fg_color", None)
292
+ if fg_color:
293
+ self.__fg_color: Optional[Color] = Color(fg_color)
294
+ elif initialize:
295
+ self.__fg_color = None
296
+
297
+ bg_color = self.__kwargs.pop("bg_color", None)
298
+ if bg_color:
299
+ self.__bg_color: Optional[Color] = Color(bg_color)
300
+ elif initialize:
301
+ self.__bg_color = None
302
+
303
+ def __update_font(self, initialize: bool) -> None:
304
+ font_size = self.__kwargs.pop("font_size", None)
305
+ if font_size:
306
+ self.__font_size = normalize_enum(
307
+ font_size,
308
+ FontSize,
309
+ validate=False,
310
+ default=FontSize.NONE,
311
+ )
312
+ elif initialize:
313
+ self.__font_size = FontSize.NONE
314
+ self.__validate_attr("font_size", (FontSize, str))
315
+
316
+ font_style = self.__kwargs.pop("font_style", None)
317
+ if font_style:
318
+ self.__font_style = normalize_enum(font_style, FontStyle, default=FontStyle.NORMAL)
319
+ elif initialize:
320
+ self.__font_style = FontStyle.NORMAL
321
+ self.__validate_attr("font_style", FontStyle)
322
+
323
+ font_weight = self.__kwargs.pop("font_weight", None)
324
+ if font_weight:
325
+ self.__font_weight = normalize_enum(font_weight, FontWeight, default=FontWeight.NORMAL)
326
+ elif initialize:
327
+ self.__font_weight = FontWeight.NORMAL
328
+ self.__validate_attr("font_weight", FontWeight)
329
+
330
+ def __update_align(self, initialize: bool) -> None:
331
+ align = self.__kwargs.pop("align", None)
332
+ if align:
333
+ self.__align = normalize_enum(align, Align, default=Align.AUTO)
334
+ elif initialize:
335
+ self.__align = Align.AUTO
336
+ self.__validate_attr("align", Align)
337
+
338
+ valign = self.__kwargs.pop("vertical_align", None)
339
+ if valign:
340
+ self.__valign = normalize_enum(valign, VerticalAlign, default=VerticalAlign.BASELINE)
341
+ elif initialize:
342
+ self.__valign = VerticalAlign.BASELINE
343
+ self.__validate_attr("vertical_align", VerticalAlign)
344
+
345
+ def __update_misc(self, initialize: bool) -> None:
346
+ padding = self.__kwargs.pop("padding", None)
347
+ if padding is not None:
348
+ self.__padding = padding
349
+ elif initialize:
350
+ self.__padding = None
351
+
352
+ decoration_line = self.__kwargs.pop("decoration_line", None)
353
+ if decoration_line:
354
+ self.__decoration_line = normalize_enum(
355
+ decoration_line, DecorationLine, default=DecorationLine.NONE
356
+ )
357
+ elif initialize:
358
+ self.__decoration_line = DecorationLine.NONE
359
+ self.__validate_attr("decoration_line", DecorationLine)
360
+
361
+ thousand_separator = self.__kwargs.pop("thousand_separator", None)
362
+ if thousand_separator:
363
+ self.__thousand_separator = _normalize_thousand_separator(thousand_separator)
364
+ elif initialize:
365
+ self.__thousand_separator = ThousandSeparator.NONE
366
+ self.__validate_attr("thousand_separator", ThousandSeparator)
367
+
368
+ def __validate_attr(self, attr_name: str, expected_type: Any) -> None:
369
+ value = getattr(self, attr_name)
370
+ if isinstance(expected_type, (list, tuple)):
371
+ expected = " or ".join(c.__name__ for c in expected_type)
372
+ else:
373
+ expected = expected_type.__name__
374
+
375
+ if not isinstance(value, expected_type):
376
+ raise TypeError(f"{attr_name} must be instance of {expected}: actual={type(value)}")
env-llmeval/lib/python3.10/site-packages/pytablewriter/style/_theme.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import pkgutil
3
+ import re
4
+ from typing import Any, Dict, NamedTuple, Optional, Sequence
5
+
6
+ from .._logger import logger
7
+ from ..style import Cell, Style
8
+
9
+
10
+ try:
11
+ from typing import Protocol
12
+ except ImportError:
13
+ # typing.Protocol is only available starting from Python 3.8.
14
+ from .._typing import Protocol # type: ignore
15
+
16
+ PLUGIN_NAME_PEFIX = "pytablewriter"
17
+ PLUGIN_NAME_SUFFIX = "theme"
18
+ KNOWN_PLUGINS = (
19
+ f"{PLUGIN_NAME_PEFIX}_altrow_{PLUGIN_NAME_SUFFIX}",
20
+ f"{PLUGIN_NAME_PEFIX}_altcol_{PLUGIN_NAME_SUFFIX}",
21
+ )
22
+
23
+
24
+ class StyleFilterFunc(Protocol):
25
+ def __call__(self, cell: Cell, **kwargs: Any) -> Optional[Style]:
26
+ ...
27
+
28
+
29
+ class ColSeparatorStyleFilterFunc(Protocol):
30
+ def __call__(
31
+ self, left_cell: Optional[Cell], right_cell: Optional[Cell], **kwargs: Any
32
+ ) -> Optional[Style]:
33
+ ...
34
+
35
+
36
+ class CheckStyleFilterKeywordArgsFunc(Protocol):
37
+ def __call__(self, **kwargs: Any) -> None:
38
+ ...
39
+
40
+
41
+ class Theme(NamedTuple):
42
+ style_filter: Optional[StyleFilterFunc]
43
+ col_separator_style_filter: Optional[ColSeparatorStyleFilterFunc]
44
+ check_style_filter_kwargs: Optional[CheckStyleFilterKeywordArgsFunc]
45
+
46
+
47
+ def list_themes() -> Sequence[str]:
48
+ return list(load_ptw_plugins())
49
+
50
+
51
+ def load_ptw_plugins() -> Dict[str, Theme]:
52
+ plugin_regexp = re.compile(
53
+ rf"^{PLUGIN_NAME_PEFIX}[_-].+[_-]{PLUGIN_NAME_SUFFIX}", re.IGNORECASE
54
+ )
55
+
56
+ discovered_plugins = {
57
+ name: importlib.import_module(name)
58
+ for _finder, name, _ispkg in pkgutil.iter_modules()
59
+ if plugin_regexp.search(name) is not None
60
+ }
61
+
62
+ logger.debug(f"discovered_plugins: {list(discovered_plugins)}")
63
+
64
+ themes: Dict[str, Theme] = {}
65
+ for theme, plugin in discovered_plugins.items():
66
+ style_filter = plugin.style_filter if hasattr(plugin, "style_filter") else None
67
+ col_sep_style_filter = (
68
+ plugin.col_separator_style_filter
69
+ if hasattr(plugin, "col_separator_style_filter")
70
+ else None
71
+ )
72
+ check_kwargs_func = (
73
+ plugin.check_style_filter_kwargs
74
+ if hasattr(plugin, "check_style_filter_kwargs")
75
+ else None
76
+ )
77
+ themes[theme] = Theme(style_filter, col_sep_style_filter, check_kwargs_func)
78
+
79
+ return themes
80
+
81
+
82
+ def fetch_theme(plugin_name: str) -> Theme:
83
+ loaded_themes = load_ptw_plugins()
84
+ theme_regexp = re.compile(
85
+ rf"^{PLUGIN_NAME_PEFIX}[_-]{plugin_name}[_-]{PLUGIN_NAME_SUFFIX}", re.IGNORECASE
86
+ )
87
+ matched_theme = None
88
+
89
+ for loaded_theme in loaded_themes:
90
+ if theme_regexp.search(loaded_theme):
91
+ matched_theme = loaded_theme
92
+ break
93
+ else:
94
+ err_msgs = [f"{plugin_name} theme is not installed."]
95
+
96
+ if plugin_name in KNOWN_PLUGINS:
97
+ err_msgs.append(f"try 'pip install {plugin_name}' to install the theme.")
98
+
99
+ raise RuntimeError(" ".join(err_msgs))
100
+
101
+ return loaded_themes[matched_theme]
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_common.cpython-310.pyc ADDED
Binary file (411 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_elasticsearch.cpython-310.pyc ADDED
Binary file (6.63 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_interface.cpython-310.pyc ADDED
Binary file (3.56 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_msgfy.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_null.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/__pycache__/_table_writer.cpython-310.pyc ADDED
Binary file (37.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.33 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_asciidoc.cpython-310.pyc ADDED
Binary file (5.62 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pytablewriter/writer/text/__pycache__/_borderless.cpython-310.pyc ADDED
Binary file (1.58 kB). View file