예제 #1
0
 def preprocess(cls, wrt):
     if isinstance(wrt, Basic):
         return [str(wrt)]
     elif isinstance(wrt, str):
         wrt = wrt.strip()
         if wrt.endswith(','):
             raise OptionError('Bad input: missing parameter.')
         if not wrt:
             return []
         return [gen for gen in cls._re_split.split(wrt)]
     elif hasattr(wrt, '__getitem__'):
         return list(map(str, wrt))
     else:
         raise OptionError("invalid argument for 'wrt' option")
예제 #2
0
def test_pickling_polys_errors():
    # TODO: TypeError: __init__() takes at least 3 arguments (1 given)
    # for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)):
    #    check(c)

    # TODO: TypeError: can't pickle instancemethod objects
    # for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)):
    #    check(c)

    for c in (HeuristicGCDFailed, HeuristicGCDFailed(), HomomorphismFailed,
              HomomorphismFailed(), IsomorphismFailed, IsomorphismFailed(),
              ExtraneousFactors, ExtraneousFactors(), EvaluationFailed,
              EvaluationFailed(),
              RefinementFailed, RefinementFailed(), CoercionFailed,
              CoercionFailed(), NotInvertible, NotInvertible(), NotReversible,
              NotReversible(), NotAlgebraic, NotAlgebraic(), DomainError,
              DomainError(), PolynomialError, PolynomialError(),
              UnificationFailed, UnificationFailed(), GeneratorsError,
              GeneratorsError(), GeneratorsNeeded, GeneratorsNeeded()):
        check(c)

    # TODO: PicklingError: Can't pickle <function <lambda> at 0x38578c0>: it's not found as __main__.<lambda>
    # for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)):
    #    check(c)

    for c in (UnivariatePolynomialError, UnivariatePolynomialError(),
              MultivariatePolynomialError, MultivariatePolynomialError()):
        check(c)

    # TODO: TypeError: __init__() takes at least 3 arguments (1 given)
    # for c in (PolificationFailed, PolificationFailed({}, x, x, False)):
    #    check(c)

    for c in (OptionError, OptionError(), FlagError, FlagError()):
        check(c)
예제 #3
0
def allowed_flags(args, flags):
    """
    Allow specified flags to be used in the given context.

    Examples
    ========

    >>> from diofant.polys.domains import ZZ

    >>> 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.keys():
        try:
            if Options.__options__[arg].is_Flag and arg not in flags:
                raise FlagError("'%s' flag is not allowed in this context" %
                                arg)
        except KeyError:
            raise OptionError("'%s' is not a valid option" % arg)
예제 #4
0
 def preprocess(cls, value):
     if value in [True, False]:
         return bool(value)
     else:
         raise OptionError(
             "'%s' must have a boolean value assigned, got %s" %
             (cls.option, value))
예제 #5
0
 def preprocess(cls, sort):
     if isinstance(sort, str):
         return [gen.strip() for gen in sort.split('>')]
     elif hasattr(sort, '__getitem__'):
         return list(map(str, sort))
     else:
         raise OptionError("invalid argument for 'sort' option")
예제 #6
0
        def preprocess_options(args):
            for option, value in args.items():
                try:
                    cls = self.__options__[option]
                except KeyError:
                    raise OptionError("'%s' is not a valid option" % option)

                if issubclass(cls, Flag):
                    if flags is None or option not in flags:
                        if strict:
                            raise OptionError(
                                "'%s' flag is not allowed in this context" %
                                option)

                if value is not None:
                    self[option] = cls.preprocess(value)
예제 #7
0
    def preprocess(cls, modulus):
        modulus = sympify(modulus)

        if modulus.is_Integer and modulus > 0:
            return int(modulus)
        else:
            raise OptionError("'modulus' must a positive integer, got %s" %
                              modulus)
예제 #8
0
    def preprocess(cls, extension):
        if extension == 1:
            return bool(extension)
        elif extension == 0:
            raise OptionError("'False' is an invalid argument for 'extension'")
        else:
            if not hasattr(extension, '__iter__'):
                extension = {extension}
            else:
                if not extension:
                    extension = None
                else:
                    extension = set(extension)

            return extension
예제 #9
0
 def preprocess(cls, method):
     if isinstance(method, str):
         return method.lower()
     else:
         raise OptionError("expected a string, got %s" % method)
예제 #10
0
 def preprocess(cls, symbols):
     if hasattr(symbols, '__iter__'):
         return iter(symbols)
     else:
         raise OptionError(
             "expected an iterator or iterable container, got %s" % symbols)
예제 #11
0
 def preprocess(cls, gen):
     if isinstance(gen, (Basic, int)):
         return gen
     else:
         raise OptionError("invalid argument for 'gen' option")
예제 #12
0
    def preprocess(cls, domain):
        if isinstance(domain, diofant.polys.domains.Domain):
            return domain
        elif hasattr(domain, 'to_domain'):
            return domain.to_domain()
        elif isinstance(domain, str):
            if domain in ['Z', 'ZZ']:
                return diofant.polys.domains.ZZ

            if domain in ['Q', 'QQ']:
                return diofant.polys.domains.QQ

            if domain == 'EX':
                return diofant.polys.domains.EX

            r = cls._re_realfield.match(domain)

            if r is not None:
                _, _, prec = r.groups()

                if prec is None:
                    return diofant.polys.domains.RR
                else:
                    return diofant.polys.domains.RealField(int(prec))

            r = cls._re_complexfield.match(domain)

            if r is not None:
                _, _, prec = r.groups()

                if prec is None:
                    return diofant.polys.domains.CC
                else:
                    return diofant.polys.domains.ComplexField(int(prec))

            r = cls._re_finitefield.match(domain)

            if r is not None:
                return diofant.polys.domains.FF(int(r.groups()[1]))

            r = cls._re_polynomial.match(domain)

            if r is not None:
                ground, gens = r.groups()

                gens = list(map(sympify, gens.split(',')))

                if ground in ['Z', 'ZZ']:
                    return diofant.polys.domains.ZZ.poly_ring(*gens)
                else:
                    return diofant.polys.domains.QQ.poly_ring(*gens)

            r = cls._re_fraction.match(domain)

            if r is not None:
                ground, gens = r.groups()

                gens = list(map(sympify, gens.split(',')))

                if ground in ['Z', 'ZZ']:
                    return diofant.polys.domains.ZZ.frac_field(*gens)
                else:
                    return diofant.polys.domains.QQ.frac_field(*gens)

            r = cls._re_algebraic.match(domain)

            if r is not None:
                gens = list(map(sympify, r.groups()[1].split(',')))
                return diofant.polys.domains.QQ.algebraic_field(*gens)

        raise OptionError('expected a valid domain specification, got %s' %
                          domain)
예제 #13
0
    def __init__(self, gens, args, flags=None, strict=False):
        dict.__init__(self)

        if gens and args.get('gens', ()):
            raise OptionError(
                "both '*gens' and keyword argument 'gens' supplied")
        elif 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:
                    raise OptionError("'%s' is not a valid option" % option)

                if issubclass(cls, Flag):
                    if flags is None or option not in flags:
                        if strict:
                            raise OptionError(
                                "'%s' flag is not allowed in this context" %
                                option)

                if value is not None:
                    self[option] = cls.preprocess(value)

        preprocess_options(args)

        for key, value in dict(defaults).items():
            if key in self:
                del defaults[key]
            else:
                for option in self.keys():
                    cls = self.__options__[option]

                    if key in cls.excludes:
                        del defaults[key]
                        break

        preprocess_options(defaults)

        for option in self.keys():
            cls = self.__options__[option]

            for require_option in cls.requires:
                if self.get(require_option) is None:
                    raise OptionError(
                        "'%s' option is only allowed together with '%s'" %
                        (option, require_option))

            for exclude_option in cls.excludes:
                if self.get(exclude_option) is not None:
                    raise OptionError(
                        "'%s' option is not allowed together with '%s'" %
                        (option, exclude_option))

        for option in self.__order__:
            self.__options__[option].postprocess(self)