-
Notifications
You must be signed in to change notification settings - Fork 0
/
rat.py
562 lines (474 loc) Β· 21.4 KB
/
rat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
"""Routines for rational functions."""
from __future__ import annotations
import functools
from fractions import Fraction
from typing import Any, FrozenSet, Iterable, Sequence, Union, overload
from .array import _create_raw_int_array, _create_raw_var_array
from .jvm import jvm
from .poly import Polynomial
from .var import Variable, VariableLike
from .varset import VariableSet, VariableSetLike
_RawRationalFunction = jvm.find_class("com.github.tueda.donuts.RationalFunction")
_JavaError = jvm.java_error_class
_RAW_ZERO = _RawRationalFunction()
_RAW_ONE = _RawRationalFunction(1)
_RAW_MINUS_ONE = _RawRationalFunction(-1)
def _raw_rationalfunction_from_short_int(value: int) -> Any:
if value == 0:
return _RAW_ZERO
if value == 1:
return _RAW_ONE
if value == -1:
return _RAW_MINUS_ONE
return _raw_rationalfunction_from_short_int_impl(value)
@functools.lru_cache(maxsize=1024)
def _raw_rationalfunction_from_short_int_impl(value: int) -> Any:
return _RawRationalFunction(value)
@functools.lru_cache(maxsize=1024)
def _raw_rationalfunction_from_str(value: str) -> Any:
return _RawRationalFunction(value)
class RationalFunction:
"""Rational function."""
__slots__ = ("_raw",)
def __init__(
self,
numerator: Union[
RationalFunction, Polynomial, Variable, Fraction, int, str, None
] = None,
denominator: Union[Polynomial, Variable, int, None] = None,
) -> None:
"""Construct a rational function."""
if denominator is None:
if numerator is None:
self._raw = _RAW_ZERO
elif isinstance(numerator, int):
if Polynomial._is_short_int(numerator):
self._raw = _raw_rationalfunction_from_short_int(numerator)
else:
self._raw = _RawRationalFunction(str(numerator))
elif isinstance(numerator, str):
try:
self._raw = _RawRationalFunction(numerator)
except _JavaError as e:
raise ValueError("invalid string for rational function") from e
elif isinstance(numerator, Fraction):
if Polynomial._is_short_int(
numerator.numerator
) and Polynomial._is_short_int(numerator.denominator):
self._raw = _RawRationalFunction(
numerator.numerator, numerator.denominator
)
else:
self._raw = _RawRationalFunction(
Polynomial(numerator.numerator)._raw,
Polynomial(numerator.denominator)._raw,
)
elif isinstance(numerator, Variable):
self._raw = _raw_rationalfunction_from_str(numerator._name)
elif isinstance(numerator, Polynomial):
self._raw = _RawRationalFunction(numerator._raw)
elif isinstance(numerator, RationalFunction):
self._raw = numerator._raw
else:
raise TypeError(f"invalid numerator: `{numerator}`")
else:
if isinstance(numerator, (RationalFunction, Fraction, str)):
raise TypeError(
f"invalid numerator as denominator is given: `{numerator}`"
)
if (
isinstance(numerator, int)
and isinstance(denominator, int)
and Polynomial._is_short_int(numerator)
and Polynomial._is_short_int(denominator)
):
if denominator == 0:
raise ZeroDivisionError("division by zero")
self._raw = _RawRationalFunction(numerator, denominator)
else:
num = Polynomial(numerator)
den = Polynomial(denominator)
if den.is_zero:
raise ZeroDivisionError("division by zero")
self._raw = _RawRationalFunction(num._raw, den._raw)
@staticmethod
def _new(raw: Any) -> RationalFunction:
"""Construct a rational function from a raw object."""
obj = RationalFunction()
obj._raw = raw
return obj
def __getstate__(self) -> Any:
"""Get the object state."""
return str(self._raw.toString())
def __setstate__(self, state: Any) -> None:
"""Set the object state."""
self._raw = _RawRationalFunction(state)
def __str__(self) -> str:
"""Return the string representation."""
return str(self._raw.toString())
def __repr__(self) -> str:
"""Return the "official" string representation."""
return f"RationalFunction('{str(self)}')"
def __hash__(self) -> int:
"""Return the hash code."""
if self.is_fraction:
return hash(self.as_fraction)
if self.is_polynomial:
return hash(self.as_polynomial)
return self._raw.hashCode() # type: ignore
def __bool__(self) -> bool:
"""Return `True` for non-zero rational functions."""
return not self.is_zero
def __pos__(self) -> RationalFunction:
"""Return ``+ self``."""
return self
def __neg__(self) -> RationalFunction:
"""Return ``- self``."""
return RationalFunction._new(self._raw.negate())
def __add__(
self, other: Union[RationalFunction, Polynomial, Variable, Fraction, int]
) -> RationalFunction:
"""Return ``self + other``."""
if isinstance(other, RationalFunction):
return RationalFunction._new(self._raw.add(other._raw))
elif isinstance(other, (Polynomial, Variable, Fraction, int)):
return self + RationalFunction(other)
return NotImplemented # type: ignore
def __radd__(
self, other: Union[Polynomial, Variable, Fraction, int]
) -> RationalFunction:
"""Return ``other + self``."""
if isinstance(other, (Polynomial, Variable, Fraction, int)):
return RationalFunction(other) + self
return NotImplemented # type: ignore
def __sub__(
self, other: Union[RationalFunction, Polynomial, Variable, Fraction, int]
) -> RationalFunction:
"""Return ``self - other``."""
if isinstance(other, RationalFunction):
return RationalFunction._new(self._raw.subtract(other._raw))
elif isinstance(other, (Polynomial, Variable, Fraction, int)):
return self - RationalFunction(other)
return NotImplemented # type: ignore
def __rsub__(
self, other: Union[Polynomial, Variable, Fraction, int]
) -> RationalFunction:
"""Return ``other - self``."""
if isinstance(other, (Polynomial, Variable, Fraction, int)):
return RationalFunction(other) - self
return NotImplemented # type: ignore
def __mul__(
self, other: Union[RationalFunction, Polynomial, Variable, Fraction, int]
) -> RationalFunction:
"""Return ``self * other``."""
if isinstance(other, RationalFunction):
return RationalFunction._new(self._raw.multiply(other._raw))
elif isinstance(other, (Polynomial, Variable, Fraction, int)):
return self * RationalFunction(other)
return NotImplemented # type: ignore
def __rmul__(
self, other: Union[Polynomial, Variable, Fraction, int]
) -> RationalFunction:
"""Return ``other * self``."""
if isinstance(other, (Polynomial, Variable, Fraction, int)):
return RationalFunction(other) * self
return NotImplemented # type: ignore
def __truediv__(
self, other: Union[RationalFunction, Polynomial, Variable, Fraction, int]
) -> RationalFunction:
"""Return ``self / other``."""
if isinstance(other, RationalFunction):
if other.is_zero:
raise ZeroDivisionError("division by zero")
return RationalFunction._new(self._raw.divide(other._raw))
elif isinstance(other, (Polynomial, Variable, Fraction, int)):
return self / RationalFunction(other)
return NotImplemented # type: ignore
def __rtruediv__(
self, other: Union[Polynomial, Variable, Fraction, int]
) -> RationalFunction:
"""Return ``other / self``."""
if isinstance(other, (Polynomial, Variable, Fraction, int)):
return RationalFunction(other) / self
return NotImplemented # type: ignore
def __pow__(self, other: int) -> RationalFunction:
"""Return ``self ** other``."""
if isinstance(other, int):
if other <= -1 and self.is_zero:
raise ZeroDivisionError("division by zero")
return RationalFunction._new(self._raw.pow(other))
return NotImplemented # type: ignore
def __eq__(self, other: object) -> bool:
"""Return ``self == other``."""
if isinstance(other, RationalFunction):
return self._raw.equals(other._raw) # type: ignore
elif isinstance(other, (Polynomial, Variable, Fraction, int)):
return self == RationalFunction(other)
return NotImplemented
@property
def numerator(self) -> Polynomial:
"""Return the numerator."""
return Polynomial._new(self._raw.getNumerator())
@property
def denominator(self) -> Polynomial:
"""Return the denominator."""
return Polynomial._new(self._raw.getDenominator())
@property
def is_zero(self) -> bool:
"""Return `True` if the rational function is zero."""
return self._raw.isZero() # type: ignore
@property
def is_one(self) -> bool:
"""Return `True` if the rational function is one."""
return self._raw.isOne() # type: ignore
@property
def is_minus_one(self) -> bool:
"""Return `True` if the rational function is minus one."""
return self._raw.isMinusOne() # type: ignore
@property
def is_integer(self) -> bool:
"""Return `True` if the rational function is an integer."""
return self._raw.isInteger() # type: ignore
@property
def is_fraction(self) -> bool:
"""Return `True` if the rational function is a rational number."""
return self._raw.isConstant() # type: ignore
@property
def is_polynomial(self) -> bool:
"""Return `True` if the rational function is a polynomial."""
return self._raw.isPolynomial() # type: ignore
@property
def is_variable(self) -> bool:
"""Return `True` if the rational function is a variable."""
return self.is_polynomial and self.numerator.is_variable
@property
def as_integer(self) -> int:
"""Cast the rational function to an integer."""
if self.is_integer:
return self.numerator.as_integer
raise ValueError("not an integer")
@property
def as_fraction(self) -> Fraction:
"""Cast the rational function to a rational number."""
if self.is_fraction:
return Fraction(self.numerator.as_integer, self.denominator.as_integer)
raise ValueError("not a rational number")
@property
def as_polynomial(self) -> Polynomial:
"""Cast the rational function to a polynomial."""
if self.is_polynomial:
return self.numerator
raise ValueError("not a polynomial")
@property
def as_variable(self) -> Variable:
"""Cast the rational function to a variable."""
if self.is_variable:
return Variable._new(self._raw.getNumerator().asVariable())
raise ValueError("not a variable")
@property
def variables(self) -> FrozenSet[Variable]:
"""Return the set of variables."""
return VariableSet._frozenset_from_raw(self._raw.getVariables())
@property
def min_variables(self) -> FrozenSet[Variable]:
"""Return the set of actually used variables in this polynomial."""
return VariableSet._frozenset_from_raw(self._raw.getMinimalVariables())
@overload
def translate(self, *variables: VariableLike) -> RationalFunction:
"""Translate the rational function in terms of the given set of variables."""
...
@overload
def translate(self, variables: VariableSetLike) -> RationalFunction:
"""Translate the rational function in terms of the given set of variables."""
...
def translate(self, *variables) -> RationalFunction: # type: ignore
"""Translate the rational function in terms of the given set of variables."""
if len(variables) == 1:
xx = variables[0]
if isinstance(xx, VariableSet):
return self._translate_impl(xx._raw)
elif isinstance(xx, Iterable) and not isinstance(xx, str):
return self.translate(*xx)
if any(not isinstance(x, (str, Variable)) for x in variables):
raise TypeError("not Variable")
return self._translate_impl(VariableSet._get_raw(variables))
def _translate_impl(self, raw_varset: Any) -> RationalFunction:
try:
raw = self._raw.translate(raw_varset)
except _JavaError as e:
raise ValueError("invalid set of variables") from e
return RationalFunction._new(raw)
def subs(
self,
lhs: Union[Polynomial, Variable, str],
rhs: Union[RationalFunction, Polynomial, Variable, Fraction, int, str],
) -> RationalFunction:
"""Return the result of the given substitution."""
if isinstance(lhs, Polynomial):
if isinstance(rhs, RationalFunction):
try:
r = RationalFunction._new(self._raw.substitute(lhs._raw, rhs._raw))
except _JavaError as e:
if jvm.get_error_message(e) == "division by zero":
raise ZeroDivisionError("division by zero") from e
else:
raise ValueError("invalid lhs for substitution") from e
assert not r.denominator.is_zero # noqa: S101 # just in case
return r
elif isinstance(rhs, (Polynomial, Variable, Fraction, int, str)):
return self.subs(lhs, RationalFunction(rhs))
else:
raise TypeError("rhs is not a RationalFunction")
elif isinstance(lhs, (Variable, str)):
return self.subs(Polynomial(lhs), rhs)
else:
raise TypeError("lhs is not a Polynomial")
@overload
def evaluate(self, variable: Union[Variable, str], value: int) -> RationalFunction:
"""Return the result of setting the given variable to the specified value."""
...
@overload
def evaluate(
self, variables: Sequence[Union[Variable, str]], values: Sequence[int]
) -> RationalFunction:
"""Return the result of setting the given variables to the specified values."""
...
def evaluate(self, variables, values) -> RationalFunction: # type: ignore
"""Return the result of setting the given variables to the specified values."""
# TODO: integer overflow occurs >= 2^31.
if isinstance(variables, Sequence) and not isinstance(variables, str):
if not (isinstance(values, Sequence) and not isinstance(values, str)):
raise TypeError("values must be a sequence")
if len(variables) != len(values):
raise ValueError("variables and values have different sizes")
try:
return RationalFunction._new(
self._raw.evaluate(
_create_raw_var_array(tuple(variables)),
_create_raw_int_array(tuple(values)),
)
)
except _JavaError as e:
if jvm.get_error_message(e) == "division by zero":
raise ZeroDivisionError("division by zero") from e
raise e # pragma: no cover
if isinstance(variables, Variable):
x = variables
if not isinstance(values, int):
raise TypeError("value must be an integer")
n = values
try:
return RationalFunction._new(self._raw.evaluate(x._raw, n))
except _JavaError as e:
if jvm.get_error_message(e) == "division by zero":
raise ZeroDivisionError("division by zero") from e
raise e # pragma: no cover
if isinstance(variables, str):
return self.evaluate(Variable(variables), values)
raise TypeError("invalid variables")
@overload
def evaluate_at_zero(self, *variables: VariableLike) -> RationalFunction:
"""Return the result of setting all the given variables to zero."""
...
@overload
def evaluate_at_zero(self, variables: VariableSetLike) -> RationalFunction:
"""Return the result of setting all the given variables to zero."""
...
def evaluate_at_zero(self, *variables) -> RationalFunction: # type: ignore
"""Return the result of setting all the given variables to zero."""
if len(variables) == 1:
x = variables[0]
if isinstance(x, (Variable, VariableSet)):
try:
return RationalFunction._new(self._raw.evaluateAtZero(x._raw))
except _JavaError as e:
if jvm.get_error_message(e) == "division by zero":
raise ZeroDivisionError("division by zero") from e
raise e # pragma: no cover
if isinstance(x, Iterable) and not isinstance(x, str):
if not x:
# None of the variables are specified.
return self
return self.evaluate_at_zero(*x)
if len(variables) == 0:
# None of the variables are specified.
return self
if any(not isinstance(x, (Variable, str)) for x in variables):
raise TypeError("not Variable")
return self.evaluate_at_zero(VariableSet(*variables))
@overload
def evaluate_at_one(self, *variables: VariableLike) -> RationalFunction:
"""Return the result of setting all the given variables to unity."""
...
@overload
def evaluate_at_one(self, variables: VariableSetLike) -> RationalFunction:
"""Return the result of setting all the given variables to unity."""
...
def evaluate_at_one(self, *variables) -> RationalFunction: # type: ignore
"""Return the result of setting all the given variables to unity."""
if len(variables) == 1:
x = variables[0]
if isinstance(x, (Variable, VariableSet)):
try:
return RationalFunction._new(self._raw.evaluateAtOne(x._raw))
except _JavaError as e:
if jvm.get_error_message(e) == "division by zero":
raise ZeroDivisionError("division by zero") from e
raise e # pragma: no cover
if isinstance(x, Iterable) and not isinstance(x, str):
if not x:
# None of the variables are specified.
return self
return self.evaluate_at_one(*x)
if len(variables) == 0:
# None of the variables are specified.
return self
if any(not isinstance(x, (Variable, str)) for x in variables):
raise TypeError("not Variable")
return self.evaluate_at_one(VariableSet(*variables))
@overload
def shift(self, variable: Union[Variable, str], shift: int) -> RationalFunction:
"""Return the result of the given variable shift."""
...
@overload
def shift(
self, variables: Sequence[Union[Variable, str]], values: Sequence[int]
) -> RationalFunction:
"""Return the result of the given variable shifts."""
...
def shift(self, variables, values) -> RationalFunction: # type: ignore
"""Return the result of the given variable shifts."""
# TODO: integer overflow occurs >= 2^31.
if isinstance(variables, Sequence) and not isinstance(variables, str):
if not (isinstance(values, Sequence) and not isinstance(values, str)):
raise TypeError("values must be a sequence")
if len(variables) != len(values):
raise ValueError("variables and values have different sizes")
return RationalFunction._new(
self._raw.shift(
_create_raw_var_array(tuple(variables)),
_create_raw_int_array(tuple(values)),
)
)
if isinstance(variables, Variable):
x = variables
if not isinstance(values, int):
raise TypeError("value must be an integer")
n = values
return RationalFunction._new(self._raw.shift(x._raw, n))
if isinstance(variables, str):
return self.shift(Variable(variables), values)
raise TypeError("invalid variables")
def diff(self, x: Union[Variable, str], n: int = 1) -> RationalFunction:
"""Differentiate this rational function."""
if isinstance(x, str):
x = Variable(x)
if not isinstance(x, Variable):
raise TypeError("x must be a Variable")
if not isinstance(n, int):
raise TypeError("n must be an int")
if n < 0:
raise ValueError("n must be non-negative")
return RationalFunction._new(self._raw.derivative(x._raw, n))
# For static typing.
RationalFunctionLike = Union[RationalFunction, Polynomial, Variable, Fraction, int]