/
polyoptions.py
665 lines (462 loc) · 17.6 KB
/
polyoptions.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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
"""Options manager for :class:`~diofant.polys.polytools.Poly` and public API functions."""
import graphlib
import re
from ..core import Basic, I, sympify
from .polyerrors import FlagError, GeneratorsError, OptionError
__all__ = 'allowed_flags', 'build_options'
class Option:
"""Base class for all kinds of options."""
option: str
is_Flag = False
requires: list[str] = []
excludes: list[str] = []
after: list[str] = []
before: list[str] = []
@classmethod
def default(cls):
return
@classmethod
def preprocess(cls, option):
return # pragma: no cover
@classmethod
def postprocess(cls, options):
return
class Flag(Option):
"""Base class for all kinds of flags."""
is_Flag = True
class BooleanOption(Option):
"""An option that must have a boolean value or equivalent assigned."""
@classmethod
def preprocess(cls, option):
if option in [True, False]:
return bool(option)
raise OptionError(f"'{cls.option}' must have a boolean value "
f'assigned, got {option}')
class OptionType(type):
"""Base type for all options that does registers options."""
def __init__(cls, *args, **kwargs):
"""Initialize cls."""
super().__init__(cls)
@property
def getter(a):
try:
return a[cls.option]
except KeyError:
return cls.default()
setattr(Options, cls.option, getter)
Options.__options__[cls.option] = cls
class Options(dict):
"""
Options manager for polynomial manipulation module.
Examples
========
>>> Options((x, y, z), {'domain': 'ZZ'})
{'auto': False, 'domain': ZZ, 'gens': (x, y, z)}
>>> build_options((x, y, z), {'domain': 'ZZ'})
{'auto': False, 'domain': ZZ, 'gens': (x, y, z)}
**Options**
* Expand --- boolean option
* Gens --- option
* Wrt --- option
* Sort --- option
* Order --- option
* Field --- boolean option
* Greedy --- boolean option
* Domain --- option
* Split --- boolean option
* Gaussian --- boolean option
* Extension --- option
* Modulus --- option
* Symmetric --- boolean option
**Flags**
* Auto --- boolean flag
* Frac --- boolean flag
* Formal --- boolean flag
* Polys --- boolean flag
* Include --- boolean flag
* Gen --- flag
"""
__order__: list[str] = []
__options__: dict[str, type[Option]] = {}
def __init__(self, gens, args, flags=None):
"""Initialize self."""
dict.__init__(self)
if gens and args.get('gens', ()):
raise OptionError("both '*gens' and keyword "
"argument 'gens' supplied")
if gens:
args = dict(args)
args['gens'] = gens
defaults = args.pop('defaults', {})
def preprocess_options(args):
for option, value in args.items():
try:
cls = self.__options__[option]
except KeyError as exc:
raise OptionError(f"'{option}' is not a "
'valid option') from exc
if value is not None:
self[option] = cls.preprocess(value)
preprocess_options(args)
for key in dict(defaults):
if key in self:
del defaults[key]
else:
for option in self:
cls = self.__options__[option]
if key in cls.excludes:
del defaults[key]
break
preprocess_options(defaults)
for option in self:
cls = self.__options__[option]
for exclude_option in cls.excludes:
if self.get(exclude_option) is not None:
raise OptionError(f"'{option}' option is not allowed together with '{exclude_option}'")
for option in self.__order__:
self.__options__[option].postprocess(self)
@classmethod
def _init_dependencies_order(cls):
"""Resolve the order of options' processing."""
if not cls.__order__:
vertices, edges = [], []
for name, option in cls.__options__.items():
vertices.append(name)
for _name in option.after:
edges.append((_name, name))
for _name in option.before:
edges.append((name, _name))
graph = {v: {_[0] for _ in edges if _[1] == v} for v in vertices}
try:
cls.__order__ = list(graphlib.TopologicalSorter(graph).static_order())
except ValueError as exc:
raise RuntimeError('cycle detected in diofant.polys'
' options framework') from exc
def clone(self, updates={}):
"""Clone ``self`` and update specified options."""
obj = dict.__new__(self.__class__)
for option, value in self.items():
obj[option] = value
for option, value in updates.items():
obj[option] = value
return obj
def __setattr__(self, attr, value):
if attr in self.__options__:
self[attr] = value
else:
super().__setattr__(attr, value)
@property
def args(self):
args = {}
for option, value in self.items():
if value is not None and option != 'gens':
cls = self.__options__[option]
if not issubclass(cls, Flag):
args[option] = value
return args
@property
def options(self):
options = {}
for option, cls in self.__options__.items():
if not issubclass(cls, Flag):
options[option] = getattr(self, option)
return options
@property
def flags(self):
flags = {}
for option, cls in self.__options__.items():
if issubclass(cls, Flag):
flags[option] = getattr(self, option)
return flags
class Expand(BooleanOption, metaclass=OptionType):
"""``expand`` option to polynomial manipulation functions."""
option = 'expand'
@classmethod
def default(cls):
return True
class Gens(Option, metaclass=OptionType):
"""``gens`` option to polynomial manipulation functions."""
option = 'gens'
@classmethod
def default(cls):
return ()
@classmethod
def preprocess(cls, option):
if isinstance(option, Basic):
option = option,
if option == (None,):
return ()
if len(set(option)) < len(option):
raise GeneratorsError(f'duplicated generators: {option}')
if any(gen.is_commutative is False for gen in option):
raise GeneratorsError(f'non-commutative generators: {option}')
return tuple(option)
class Wrt(Option, metaclass=OptionType):
"""``wrt`` option to polynomial manipulation functions."""
option = 'wrt'
_re_split = re.compile(r'\s*,\s*|\s+')
@classmethod
def preprocess(cls, option):
if isinstance(option, Basic):
return [str(option)]
if isinstance(option, str):
option = option.strip()
if option.endswith(','):
raise OptionError('Bad input: missing parameter.')
if not option:
return []
return list(cls._re_split.split(option))
if hasattr(option, '__getitem__'):
return list(map(str, option))
raise OptionError("invalid argument for 'wrt' option")
class Sort(Option, metaclass=OptionType):
"""``sort`` option to polynomial manipulation functions."""
option = 'sort'
@classmethod
def default(cls):
return []
@classmethod
def preprocess(cls, option):
if isinstance(option, str):
return [gen.strip() for gen in option.split('>')]
if hasattr(option, '__getitem__'):
return list(map(str, option))
raise OptionError("invalid argument for 'sort' option")
class Order(Option, metaclass=OptionType):
"""``order`` option to polynomial manipulation functions."""
option = 'order'
@classmethod
def default(cls):
from .orderings import lex
return lex
@classmethod
def preprocess(cls, option):
from .orderings import monomial_key
return monomial_key(option)
class Field(BooleanOption, metaclass=OptionType):
"""``field`` option to polynomial manipulation functions."""
option = 'field'
excludes = ['domain', 'split', 'gaussian']
class Greedy(BooleanOption, metaclass=OptionType):
"""``greedy`` option to polynomial manipulation functions."""
option = 'greedy'
excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus']
class Composite(BooleanOption, metaclass=OptionType):
"""``composite`` option to polynomial manipulation functions."""
option = 'composite'
@classmethod
def default(cls):
return
excludes = ['domain', 'split', 'gaussian', 'modulus']
class Domain(Option, metaclass=OptionType):
"""``domain`` option to polynomial manipulation functions."""
option = 'domain'
excludes = ['field', 'greedy', 'split', 'gaussian', 'extension']
after = ['gens']
_re_realfield = re.compile(r'^(R|RR)(_(\d+))?$')
_re_complexfield = re.compile(r'^(C|CC)(_(\d+))?$')
_re_finitefield = re.compile(r'^(FF|GF)\((\d+)\)$')
_re_polynomial = re.compile(r'^(Z|ZZ|Q|QQ)\[(.+)\]$')
_re_fraction = re.compile(r'^(Z|ZZ|Q|QQ)\((.+)\)$')
_re_algebraic = re.compile(r'^(Q|QQ)\<(.+)\>$')
@classmethod
def preprocess(cls, option):
from .. import domains
if isinstance(option, domains.Domain):
return option
if isinstance(option, str):
if option in ['Z', 'ZZ']:
return domains.ZZ
if option in ['Q', 'QQ']:
return domains.QQ
if option == 'EX':
return domains.EX
r = cls._re_realfield.match(option)
if r is not None:
_, _, prec = r.groups()
if prec is None:
return domains.RR
return domains.RealField(int(prec))
r = cls._re_complexfield.match(option)
if r is not None:
_, _, prec = r.groups()
if prec is None:
return domains.CC
return domains.ComplexField(int(prec))
r = cls._re_finitefield.match(option)
if r is not None:
return domains.FF(int(r.groups()[1]))
r = cls._re_polynomial.match(option)
if r is not None:
ground, gens = r.groups()
gens = list(map(sympify, gens.split(',')))
if ground in ['Z', 'ZZ']:
return domains.ZZ.inject(*gens)
return domains.QQ.inject(*gens)
r = cls._re_fraction.match(option)
if r is not None:
ground, gens = r.groups()
gens = list(map(sympify, gens.split(',')))
if ground in ['Z', 'ZZ']:
return domains.ZZ.inject(*gens).field
return domains.QQ.inject(*gens).field
r = cls._re_algebraic.match(option)
if r is not None:
gens = list(map(sympify, r.groups()[1].split(',')))
return domains.QQ.algebraic_field(*gens)
raise OptionError('expected a valid domain specification, '
f'got {option}')
@classmethod
def postprocess(cls, options):
from .. import domains
from ..domains.compositedomain import CompositeDomain
if 'gens' in options and 'domain' in options and isinstance(options['domain'], CompositeDomain) and \
(set(options['domain'].symbols) & set(options['gens'])):
raise GeneratorsError('ground domain and generators '
'interfere together')
if ('gens' not in options or not options['gens']) and \
'domain' in options and options['domain'] == domains.EX:
raise GeneratorsError('you have to provide generators because'
' EX domain was requested')
class Split(BooleanOption, metaclass=OptionType):
"""``split`` option to polynomial manipulation functions."""
option = 'split'
excludes = ['field', 'greedy', 'domain', 'gaussian', 'extension', 'modulus']
@classmethod
def postprocess(cls, options):
if 'split' in options:
raise NotImplementedError("'split' option is not implemented yet")
class Gaussian(BooleanOption, metaclass=OptionType):
"""``gaussian`` option to polynomial manipulation functions."""
option = 'gaussian'
excludes = ['field', 'greedy', 'domain', 'split', 'extension', 'modulus']
@classmethod
def postprocess(cls, options):
if 'gaussian' in options and options['gaussian'] is True:
options['extension'] = {I}
Extension.postprocess(options)
class Extension(Option, metaclass=OptionType):
"""``extension`` option to polynomial manipulation functions."""
option = 'extension'
excludes = ['greedy', 'domain', 'split', 'gaussian', 'modulus']
@classmethod
def preprocess(cls, option):
if option == 1:
return bool(option)
if option == 0:
return bool(option)
if not hasattr(option, '__iter__'):
option = {option}
else:
if not option:
option = None
else:
option = set(option)
return option
@classmethod
def postprocess(cls, options):
from .. import domains
if 'extension' in options and options['extension'] not in (True, False):
options['domain'] = domains.QQ.algebraic_field(
*options['extension'])
class Modulus(Option, metaclass=OptionType):
"""``modulus`` option to polynomial manipulation functions."""
option = 'modulus'
excludes = ['greedy', 'split', 'domain', 'gaussian', 'extension']
@classmethod
def preprocess(cls, option):
option = sympify(option)
if option.is_Integer and option > 0:
return int(option)
raise OptionError(f"'modulus' must a positive integer, got {option}")
@classmethod
def postprocess(cls, options):
from .. import domains
if 'modulus' in options:
modulus = options['modulus']
options['domain'] = domains.FF(modulus)
class Auto(BooleanOption, Flag, metaclass=OptionType):
"""``auto`` flag to polynomial manipulation functions."""
option = 'auto'
after = ['field', 'domain', 'extension', 'gaussian']
@classmethod
def default(cls):
return True
@classmethod
def postprocess(cls, options):
if ('domain' in options or 'field' in options) and 'auto' not in options:
options['auto'] = False
class Frac(BooleanOption, Flag, metaclass=OptionType):
"""``frac`` option to polynomial manipulation functions."""
option = 'frac'
@classmethod
def default(cls):
return False
class Formal(BooleanOption, Flag, metaclass=OptionType):
"""``formal`` flag to polynomial manipulation functions."""
option = 'formal'
@classmethod
def default(cls):
return False
class Polys(BooleanOption, Flag, metaclass=OptionType):
"""``polys`` flag to polynomial manipulation functions."""
option = 'polys'
class Include(BooleanOption, Flag, metaclass=OptionType):
"""``include`` flag to polynomial manipulation functions."""
option = 'include'
@classmethod
def default(cls):
return False
class Gen(Flag, metaclass=OptionType):
"""``gen`` flag to polynomial manipulation functions."""
option = 'gen'
@classmethod
def default(cls):
return 0
@classmethod
def preprocess(cls, option):
if isinstance(option, (Basic, int)):
return option
raise OptionError("invalid argument for 'gen' option")
class Method(Flag, metaclass=OptionType):
"""``method`` flag to polynomial manipulation functions."""
option = 'method'
@classmethod
def preprocess(cls, option):
if isinstance(option, str):
return option.lower()
raise OptionError(f'expected a string, got {option}')
def build_options(gens, args=None):
"""Construct options from keyword arguments or ... options."""
if args is None:
gens, args = (), gens
if len(args) != 1 or 'opt' not in args or gens:
return Options(gens, args)
return args['opt']
def allowed_flags(args, flags):
"""
Allow specified flags to be used in the given context.
Examples
========
>>> allowed_flags({'domain': ZZ}, [])
>>> allowed_flags({'domain': ZZ, 'frac': True}, [])
Traceback (most recent call last):
...
FlagError: 'frac' flag is not allowed in this context
>>> allowed_flags({'domain': ZZ, 'frac': True}, ['frac'])
"""
flags = set(flags)
for arg in args:
try:
if Options.__options__[arg].is_Flag and arg not in flags:
raise FlagError(f"'{arg}' flag is not allowed "
'in this context')
except KeyError as exc:
raise OptionError(f"'{arg}' is not a valid option") from exc
def set_defaults(options, **defaults):
"""Update options with default values."""
if 'defaults' not in options:
options = dict(options)
options['defaults'] = defaults
return options
Options._init_dependencies_order()