Пример #1
0
    def testSumOperators(self):
        "Test binary operators"

        f_0_5 = format["float"](0.5)
        f_1 = format["float"](1)
        f_2 = format["float"](2)
        f_3 = format["float"](3)
        f_6 = format["float"](6)
        f2 = FloatValue(2.0)
        fm3 = FloatValue(-3.0)

        x = Symbol("x", GEO)
        y = Symbol("y", GEO)
        z = Symbol("z", GEO)

        p0 = Product([f2, x])
        p1 = Product([x, y])

        S0 = Sum([x, y])
        S1 = Sum([x, z])

        F0 = Fraction(p0, y)

        # Test Sum '+'
        self.assertEqual(str(S0 + f2), '(%s + x + y)' % f_2)
        self.assertEqual(str(S0 + x), '(x + x + y)')
        self.assertEqual(str(S0 + p0), '(x + y + %s*x)' % f_2)
        self.assertEqual(str(S0 + S0), '(x + x + y + y)')
        self.assertEqual(str(S0 + F0), '(x + y + %s*x/y)' % f_2)

        # Test Sum '-'
        self.assertEqual(str(S0 - f2), '(x + y-%s)' % f_2)
        self.assertEqual(str(S0 - fm3), '(x + y + %s)' % f_3)
        self.assertEqual(str(S0 - x), '(x + y - x)')
        self.assertEqual(str(S0 - p0), '(x + y-%s*x)' % f_2)
        self.assertEqual(str(S0 - Product([fm3, p0])), '(x + y + %s*x)' % f_6)
        self.assertEqual(str(S0 - S0), '(x + y - (x + y))')
        self.assertEqual(str(S0 - F0), '(x + y - %s*x/y)' % f_2)

        # Test Sum '*'
        self.assertEqual(str(S0 * f2), '(%s*x + %s*y)' % (f_2, f_2))
        self.assertEqual(str(S0 * x), '(x*x + x*y)')
        self.assertEqual(str(S0 * p0), '(%s*x*x + %s*x*y)' % (f_2, f_2))
        self.assertEqual(str(S0 * S0), '(%s*x*y + x*x + y*y)' % f_2)
        self.assertEqual(str(S0 * F0), '(%s*x + %s*x*x/y)' % (f_2, f_2))

        # Test Sum '/'
        self.assertEqual(str(S0 / f2), '(%s*x + %s*y)' % (f_0_5, f_0_5))
        self.assertEqual(str(S0 / x), '(%s + y/x)' % f_1)
        self.assertEqual(str(S0 / p0), '(%s + %s*y/x)' % (f_0_5, f_0_5))
        self.assertEqual(str(S0 / p1), '(%s/x + %s/y)' % (f_1, f_1))
        self.assertEqual(str(S0 / S0), '(x + y)/(x + y)')
        self.assertEqual(str(S0 / S1), '(x + y)/(x + z)')
        # Silence output
        push_level(CRITICAL)
        self.assertRaises(Exception, S0.__truediv__, FloatValue(0))
        self.assertRaises(Exception, S0.__truediv__, F0)
        pop_level()
Пример #2
0
def testFraction():
    "Test simple fraction instance."

    f0 = FloatValue(-2.0)
    f1 = FloatValue(3.0)
    f2 = FloatValue(0)
    s0 = Symbol("x", BASIS)
    s1 = Symbol("y", GEO)

    F0 = Fraction(f1, f0)
    F1 = Fraction(f2, f0)
    F2 = Fraction(s0, s1)
    F3 = Fraction(s0, f1)
    F4 = Fraction(f0, s1)
    F5 = Fraction(f2, s1)
    F6 = Fraction(s0, s1)

    # Silence output
    push_level(CRITICAL)
    with pytest.raises(Exception):
        Fraction(f0, f2)
    with pytest.raises(Exception):
        Fraction(s0, f2)
    pop_level()

    assert repr(F0) == "Fraction(FloatValue(%s), FloatValue(%s))"\
        % (format["float"](-1.5), format["float"](1))
    assert repr(F2) == "Fraction(Symbol('x', BASIS), Symbol('y', GEO))"

    assert str(F0) == "%s" % format["float"](-1.5)
    assert str(F1) == "%s" % format["float"](0)
    assert str(F2) == "x/y"
    assert str(F3) == "x/%s" % format["float"](3)
    assert str(F4) == "-%s/y" % format["float"](2)
    assert str(F5) == "%s" % format["float"](0)

    assert F2 == F2
    assert F2 != F3
    assert F5 != F4
    assert F2 == F6

    assert F0.ops() == 0
    assert F1.ops() == 0
    assert F2.ops() == 1
    assert F3.ops() == 1
    assert F4.ops() == 1
    assert F5.ops() == 0

    # Test hash
    ll = [F2]
    d = {F2: 0}

    assert F2 in ll
    assert F2 in d
    assert F6 in ll
    assert F6 in d
Пример #3
0
def main(debug_level):
    "Call evaluate basis for a range of different elements."

    push_level(debug_level)

    # Remove old log file.
    if os.path.isfile(log_file):
        os.remove(log_file)

    # Change to temporary folder and copy form files
    if not os.path.isdir("tmp"):
        os.mkdir("tmp")
    os.chdir("tmp")

    # Create list of all elements that have to be tested.
    elements = []
    for element in single_elements:
        for shape in element["shapes"]:
            for order in element["orders"]:
                elements.append(FiniteElement(element["family"], shape, order))

    # Add the mixed elements
    elements += mixed_elements
    num_elements = len(elements)

    # Test all elements
    num_tests = 0
    msg = "Verifying evaluate_basis and evaluate_basis_derivatives for elements"
    info("\n" + msg + "\n" + len(msg) * "-")
    for i, ufl_element in enumerate(elements):
        num_tests += verify_element(num_elements, i + 1, ufl_element)

    # print results
    error = print_results(num_tests, ffc_fail, gcc_fail, run_fail, dif_cri,
                          dif_acc, correct)

    if not error:
        # Remove temporary directory
        os.chdir(os.pardir)
        shutil.rmtree("tmp")
    pop_level()

    return error
Пример #4
0
def main(debug_level):
    "Call evaluate basis for a range of different elements."

    push_level(debug_level)

    # Remove old log file.
    if os.path.isfile(log_file):
        os.remove(log_file)

    # Change to temporary folder and copy form files
    if not os.path.isdir("tmp"):
        os.mkdir("tmp")
    os.chdir("tmp")

    # Create list of all elements that have to be tested.
    elements = []
    for element in single_elements:
        for shape in element["shapes"]:
            for order in element["orders"]:
                elements.append(FiniteElement(element["family"], shape, order))

    # Add the mixed elements
    elements += mixed_elements
    num_elements = len(elements)

    # Test all elements
    num_tests = 0
    msg = "Verifying evaluate_basis and evaluate_basis_derivatives for elements"
    info("\n" + msg + "\n" + len(msg)*"-")
    for i, ufl_element in enumerate(elements):
        num_tests += verify_element(num_elements, i + 1, ufl_element)

    # print results
    error = print_results(num_tests, ffc_fail, gcc_fail, run_fail, dif_cri, dif_acc, correct)

    if not error:
        # Remove temporary directory
        os.chdir(os.pardir)
        shutil.rmtree("tmp")
    pop_level()

    return error
Пример #5
0
    def testFloatOperators(self):
        "Test binary operators"

        f0 = FloatValue(0.0)
        f2 = FloatValue(2.0)
        f3= FloatValue(3.0)
        fm1= FloatValue(-1.0)
        fm3= FloatValue(-3.0)

        x = Symbol("x", GEO)
        y = Symbol("y", GEO)
        z = Symbol("z", GEO)

        p0 = Product([f2, x])
        p1 = Product([x, y])
        p2 = Product([f2, z])
        p3 = Product([y, x, z])
        p4 = Product([fm1, f2, x])

        S0 = Sum([p0, fm3])
        S1 = Sum([x, y])
        S2 = Sum([S1, fm3])
        S3 = Sum([p4, fm3])
        S4 = Sum([fm3, Product([fm1, Sum([x, y])])])

        F0 = Fraction(f2, y)
        F1 = Fraction(FloatValue(-1.5), x)
        F2 = Fraction(fm3, S1)

        SF0 = Sum([f3, F1])
        SF1 = Sum([f3, Product([fm1, F1])])

        # Test FloatValue '+'
        self.assertEqual(str(f2 + fm3), str(fm1))
        self.assertEqual(str(f2 + fm3 + fm3 + f2 + f2), str(f0))
        self.assertEqual(str(f0 + p0), str(p0))
        self.assertEqual(str(fm3 + p0), str(S0))
        self.assertEqual(str(fm3 + S1), str(S2))
        self.assertEqual(str(f3 + F1), str(SF0))

        # Test FloatValue '-'
        self.assertEqual(str(f2 - fm3), str(FloatValue(5)))
        self.assertEqual(str(f0 - p0), str(p4))
        self.assertEqual(str(fm3 - p0), str(S3))
        self.assertEqual(str(fm3 - S1), str(S4))
        self.assertEqual(str(f3 - F1), str(SF1))

        # Test FloatValue '*', only need one because all other cases are
        # handled by 'other'
        self.assertEqual(str(f2*f2), '%s' % format["float"](4))

        # Test FloatValue '/'
        self.assertEqual(str(fm3/f2), str(FloatValue(-1.5)))
        self.assertEqual(str(f2/y), str(F0))
        self.assertEqual(str(fm3/p0), str(F1))
        self.assertEqual(str(fm3/S1), str(F2))
        # Silence output
        push_level(CRITICAL)
        self.assertRaises(Exception, f2.__truediv__, F0)
        self.assertRaises(Exception, f2.__truediv__, f0)
        self.assertRaises(Exception, f2.__truediv__, Product([f0, y]))
        pop_level()
Пример #6
0
Файл: main.py Проект: FEniCS/ffc
def main(args=None):
    """This is the commandline tool for the python module ffc."""
    if args is None:
        args = sys.argv[1:]

    # Get command-line arguments
    try:
        if "-O" in args:
            args[args.index("-O")] = "-O2"
        opts, args = getopt.getopt(args, "hIVSdvsl:r:f:O:o:q:ep",
                                   ["help", "includes", "version", "signature", "debug", "verbose", "silent",
                                    "language=", "representation=", "optimize=",
                                    "output-directory=", "quadrature-rule=", "error-control",
                                    "profile"])
    except getopt.GetoptError:
        info_usage()
        print_error("Illegal command-line arguments.")
        return 1

    # Check for --help
    if ("-h", "") in opts or ("--help", "") in opts:
        info_usage()
        return 0

    # Check for --includes
    if ("-I", "") in opts or ("--includes", "") in opts:
        print(get_include_path())
        return 0

    # Check for --version
    if ("-V", "") in opts or ("--version", "") in opts:
        info_version()
        return 0

    # Check for --signature
    if ("-S", "") in opts or ("--signature", "") in opts:
        print(get_ufc_signature())
        return 0

    # Check that we get at least one file
    if len(args) == 0:
        print_error("Missing file.")
        return 1

    # Get parameters
    parameters = default_parameters()

    # Choose WARNING as default for script
    parameters["log_level"] = WARNING

    # Set default value (not part of in parameters[])
    enable_profile = False

    # Parse command-line parameters
    for opt, arg in opts:
        if opt in ("-v", "--verbose"):
            parameters["log_level"] = INFO
        elif opt in ("-d", "--debug"):
            parameters["log_level"] = DEBUG
        elif opt in ("-s", "--silent"):
            parameters["log_level"] = ERROR
        elif opt in ("-l", "--language"):
            parameters["format"] = arg
        elif opt in ("-r", "--representation"):
            parameters["representation"] = arg
        elif opt in ("-q", "--quadrature-rule"):
            parameters["quadrature_rule"] = arg
        elif opt == "-f":
            if len(arg.split("=")) == 2:
                (key, value) = arg.split("=")
                default = parameters.get(key)
                if isinstance(default, int):
                    value = int(value)
                elif isinstance(default, float):
                    value = float(value)
                parameters[key] = value
            elif len(arg.split("==")) == 1:
                key = arg.split("=")[0]
                if key.startswith("no-"):
                    key = key[3:]
                    value = False
                else:
                    value = True
                parameters[key] = value
            else:
                info_usage()
                return 1
        elif opt in ("-O", "--optimize"):
            parameters["optimize"] = bool(int(arg))
        elif opt in ("-o", "--output-directory"):
            parameters["output_dir"] = arg
        elif opt in ("-e", "--error-control"):
            parameters["error_control"] = True
        elif opt in ("-p", "--profile"):
            enable_profile = True

    # Set log_level
    push_level(parameters["log_level"])

    # FIXME: This is terrible!
    # Set UFL precision
    #ufl.constantvalue.precision = int(parameters["precision"])

    # Print a versioning message if verbose output was requested
    if parameters["log_level"] <= INFO:
        info_version()

    # Call parser and compiler for each file
    resultcode = 0
    init_indent = ffc_logger._indent_level
    try:
        resultcode = _compile_files(args, parameters, enable_profile)
    finally:
        # Reset logging level and indent
        pop_level()
        set_indent(init_indent)

    return resultcode
Пример #7
0
def main(args=None):
    """This is the commandline tool for the python module ffc."""
    if args is None:
        args = sys.argv[1:]

    # Get command-line arguments
    try:
        if "-O" in args:
            args[args.index("-O")] = "-O2"
        opts, args = getopt.getopt(args, "hIVSdvsl:r:f:O:o:q:ep", [
            "help", "includes", "version", "signature", "debug", "verbose",
            "silent", "language=", "representation=", "optimize=",
            "output-directory=", "quadrature-rule=", "error-control", "profile"
        ])
    except getopt.GetoptError:
        info_usage()
        print_error("Illegal command-line arguments.")
        return 1

    # Check for --help
    if ("-h", "") in opts or ("--help", "") in opts:
        info_usage()
        return 0

    # Check for --includes
    if ("-I", "") in opts or ("--includes", "") in opts:
        print(get_include_path())
        return 0

    # Check for --version
    if ("-V", "") in opts or ("--version", "") in opts:
        info_version()
        return 0

    # Check for --signature
    if ("-S", "") in opts or ("--signature", "") in opts:
        print(get_ufc_signature())
        return 0

    # Check that we get at least one file
    if len(args) == 0:
        print_error("Missing file.")
        return 1

    # Get parameters
    parameters = default_parameters()

    # Choose WARNING as default for script
    parameters["log_level"] = WARNING

    # Set default value (not part of in parameters[])
    enable_profile = False

    # Parse command-line parameters
    for opt, arg in opts:
        if opt in ("-v", "--verbose"):
            parameters["log_level"] = INFO
        elif opt in ("-d", "--debug"):
            parameters["log_level"] = DEBUG
        elif opt in ("-s", "--silent"):
            parameters["log_level"] = ERROR
        elif opt in ("-l", "--language"):
            parameters["format"] = arg
        elif opt in ("-r", "--representation"):
            parameters["representation"] = arg
        elif opt in ("-q", "--quadrature-rule"):
            parameters["quadrature_rule"] = arg
        elif opt == "-f":
            if len(arg.split("=")) == 2:
                (key, value) = arg.split("=")
                default = parameters.get(key)
                if isinstance(default, int):
                    value = int(value)
                elif isinstance(default, float):
                    value = float(value)
                parameters[key] = value
            elif len(arg.split("==")) == 1:
                key = arg.split("=")[0]
                if key.startswith("no-"):
                    key = key[3:]
                    value = False
                else:
                    value = True
                parameters[key] = value
            else:
                info_usage()
                return 1
        elif opt in ("-O", "--optimize"):
            parameters["optimize"] = bool(int(arg))
        elif opt in ("-o", "--output-directory"):
            parameters["output_dir"] = arg
        elif opt in ("-e", "--error-control"):
            parameters["error_control"] = True
        elif opt in ("-p", "--profile"):
            enable_profile = True

    # Set log_level
    push_level(parameters["log_level"])

    # FIXME: This is terrible!
    # Set UFL precision
    #ufl.constantvalue.precision = int(parameters["precision"])

    # Print a versioning message if verbose output was requested
    if parameters["log_level"] <= INFO:
        info_version()

    # Call parser and compiler for each file
    resultcode = 0
    init_indent = ffc_logger._indent_level
    try:
        resultcode = _compile_files(args, parameters, enable_profile)
    finally:
        # Reset logging level and indent
        pop_level()
        set_indent(init_indent)

    return resultcode
Пример #8
0
    def testFraction(self):
        "Test simple fraction instance."

        f0 = FloatValue(-2.0)
        f1 = FloatValue(3.0)
        f2 = FloatValue(0)
        s0 = Symbol("x", BASIS)
        s1 = Symbol("y", GEO)

        F0 = Fraction(f1, f0)
        F1 = Fraction(f2, f0)
        F2 = Fraction(s0, s1)
        F3 = Fraction(s0, f1)
        F4 = Fraction(f0, s1)
        F5 = Fraction(f2, s1)
        F6 = Fraction(s0, s1)

#        print "\nTesting Fractions"
#        print "F0 = frac(%s, %s) = '%s'" %(f1, f0, F0)
#        print "F1 = frac(%s, %s) = '%s'" %(f2, f0, F1)
#        print "F2 = frac(%s, %s) = '%s'" %(s0, s1, F2)
#        print "F3 = frac(%s, %s) = '%s'" %(s0, f1, F3)
#        print "F4 = frac(%s, %s) = '%s'" %(f0, s1, F4)
#        print "F5 = frac(%s, %s) = '%s'" %(f2, s1, F5)
#        print "F6 = frac(%s, %s) = '%s'" %(s0, s1, F6)

        # Silence output
        push_level(CRITICAL)
        self.assertRaises(Exception, Fraction, f0, f2)
        self.assertRaises(Exception, Fraction, s0, f2)
        pop_level()

        self.assertEqual(repr(F0), "Fraction(FloatValue(%s), FloatValue(%s))"\
                                    % (format["float"](-1.5), format["float"](1)))
        self.assertEqual(repr(F2), "Fraction(Symbol('x', BASIS), Symbol('y', GEO))")

        self.assertEqual(str(F0), "%s" % format["float"](-1.5))
        self.assertEqual(str(F1), "%s" % format["float"](0))
        self.assertEqual(str(F2), "x/y")
        self.assertEqual(str(F3), "x/%s" % format["float"](3))
        self.assertEqual(str(F4), "-%s/y" % format["float"](2))
        self.assertEqual(str(F5), "%s" % format["float"](0))

        self.assertEqual(F2 == F2, True)
        self.assertEqual(F2 == F3, False)
        self.assertEqual(F5 != F4, True)
        self.assertEqual(F2 == F6, True)

        self.assertEqual(F0.ops(), 0)
        self.assertEqual(F1.ops(), 0)
        self.assertEqual(F2.ops(), 1)
        self.assertEqual(F3.ops(), 1)
        self.assertEqual(F4.ops(), 1)
        self.assertEqual(F5.ops(), 0)

        # Test hash
        l = [F2]
        d = {F2:0}

        self.assertEqual(F2 in l, True)
        self.assertEqual(F2 in d, True)
        self.assertEqual(F6 in l, True)
        self.assertEqual(F6 in d, True)
Пример #9
0
    def testFloatOperators(self):
        "Test binary operators"

        f0 = FloatValue(0.0)
        f2 = FloatValue(2.0)
        f3 = FloatValue(3.0)
        fm1 = FloatValue(-1.0)
        fm3 = FloatValue(-3.0)

        x = Symbol("x", GEO)
        y = Symbol("y", GEO)
        z = Symbol("z", GEO)

        p0 = Product([f2, x])
        p1 = Product([x, y])
        p2 = Product([f2, z])
        p3 = Product([y, x, z])
        p4 = Product([fm1, f2, x])

        S0 = Sum([p0, fm3])
        S1 = Sum([x, y])
        S2 = Sum([S1, fm3])
        S3 = Sum([p4, fm3])
        S4 = Sum([fm3, Product([fm1, Sum([x, y])])])

        F0 = Fraction(f2, y)
        F1 = Fraction(FloatValue(-1.5), x)
        F2 = Fraction(fm3, S1)

        SF0 = Sum([f3, F1])
        SF1 = Sum([f3, Product([fm1, F1])])

        # Test FloatValue '+'
        self.assertEqual(str(f2 + fm3), str(fm1))
        self.assertEqual(str(f2 + fm3 + fm3 + f2 + f2), str(f0))
        self.assertEqual(str(f0 + p0), str(p0))
        self.assertEqual(str(fm3 + p0), str(S0))
        self.assertEqual(str(fm3 + S1), str(S2))
        self.assertEqual(str(f3 + F1), str(SF0))

        # Test FloatValue '-'
        self.assertEqual(str(f2 - fm3), str(FloatValue(5)))
        self.assertEqual(str(f0 - p0), str(p4))
        self.assertEqual(str(fm3 - p0), str(S3))
        self.assertEqual(str(fm3 - S1), str(S4))
        self.assertEqual(str(f3 - F1), str(SF1))

        # Test FloatValue '*', only need one because all other cases are
        # handled by 'other'
        self.assertEqual(str(f2 * f2), '%s' % format["float"](4))

        # Test FloatValue '/'
        self.assertEqual(str(fm3 / f2), str(FloatValue(-1.5)))
        self.assertEqual(str(f2 / y), str(F0))
        self.assertEqual(str(fm3 / p0), str(F1))
        self.assertEqual(str(fm3 / S1), str(F2))
        # Silence output
        push_level(CRITICAL)
        self.assertRaises(Exception, f2.__truediv__, F0)
        self.assertRaises(Exception, f2.__truediv__, f0)
        self.assertRaises(Exception, f2.__truediv__, Product([f0, y]))
        pop_level()
Пример #10
0
    def testFractionOperators(self):
        "Test binary operators"

        f_0 = format["float"](0)
        f_1 = format["float"](1)
        f_2 = format["float"](2)
        f_5 = format["float"](5)

        f2 = FloatValue(2.0)
        fm3 = FloatValue(-3.0)

        x = Symbol("x", GEO)
        y = Symbol("y", GEO)

        p0 = Product([f2, x])
        p1 = Product([x, y])

        S0 = Sum([x, y])

        F0 = Fraction(f2, y)
        F1 = Fraction(x, y)
        F2 = Fraction(x, S0)
        F3 = Fraction(x, y)
        F4 = Fraction(p0, y)
        F5 = Fraction(Product([fm3, x]), y)

        # Test Fraction '+'
        self.assertEqual(str(F0 + f2), '(%s + %s/y)' % (f_2, f_2))
        self.assertEqual(str(F1 + x), '(x + x/y)')
        self.assertEqual(str(F1 + p0), '(%s*x + x/y)' % f_2)
        self.assertEqual(str(F1 + S0), '(x + y + x/y)')
        self.assertEqual(str(F1 + F3), '%s*x/y' % f_2)
        self.assertEqual(str(F0 + F1), '(%s + x)/y' % f_2)
        self.assertEqual(str(F2 + F4), '(%s*x/y + x/(x + y))' % f_2)

        # Test Fraction '-'
        self.assertEqual(str(F0 - f2), '(%s/y-%s)' % (f_2, f_2))
        self.assertEqual(str(F1 - x), '(x/y - x)')
        self.assertEqual(str(F1 - p0), '(x/y-%s*x)' % f_2)
        self.assertEqual(str(F1 - S0), '(x/y - (x + y))')
        self.assertEqual(str(F1 - F3), '%s' % f_0)
        self.assertEqual(str(F4 - F1), 'x/y')
        self.assertEqual(str(F4 - F5), '%s*x/y' % f_5)
        self.assertEqual(str(F0 - F1), '(%s - x)/y' % f_2)
        self.assertEqual(str(F2 - F4), '(x/(x + y) - %s*x/y)' % f_2)

        # Test Fraction '*'
        self.assertEqual(str(F1 * f2), '%s*x/y' % f_2)
        self.assertEqual(str(F1 * x), 'x*x/y')
        self.assertEqual(str(F1 * p1), 'x*x')
        self.assertEqual(str(F1 * S0), '(x + x*x/y)')
        self.assertEqual(repr(F1 * S0), repr(Sum([x, Fraction( Product([x, x]), y)]) ))
        self.assertEqual(str(F1 * F0), '%s*x/(y*y)' % f_2)

        # Test Fraction '/'
        self.assertEqual(str(F0 / f2), '%s/y' % f_1)
        self.assertEqual(str(F1 / x), '%s/y' % f_1)
        self.assertEqual(str(F4 / p1), '%s/(y*y)' % f_2)
        self.assertEqual(str(F4 / x), '%s/y' % f_2)
        self.assertEqual(str(F2 / y), 'x/(x*y + y*y)')
        self.assertEqual(str(F0 / S0), '%s/(x*y + y*y)' % f_2)
        # Silence output
        push_level(CRITICAL)
        self.assertRaises(Exception, F0.__truediv__, F0)
        pop_level()
Пример #11
0
def test_Float_Operators():
    "Test binary operators"

    f0 = FloatValue(0.0)
    f2 = FloatValue(2.0)
    f3 = FloatValue(3.0)
    fm1 = FloatValue(-1.0)
    fm3 = FloatValue(-3.0)

    x = Symbol("x", GEO)
    y = Symbol("y", GEO)
    z = Symbol("z", GEO)

    p0 = Product([f2, x])
    p1 = Product([x, y])
    p2 = Product([f2, z])
    p3 = Product([y, x, z])
    p4 = Product([fm1, f2, x])

    S0 = Sum([p0, fm3])
    S1 = Sum([x, y])
    S2 = Sum([S1, fm3])
    S3 = Sum([p4, fm3])
    S4 = Sum([fm3, Product([fm1, Sum([x, y])])])

    F0 = Fraction(f2, y)
    F1 = Fraction(FloatValue(-1.5), x)
    F2 = Fraction(fm3, S1)

    SF0 = Sum([f3, F1])
    SF1 = Sum([f3, Product([fm1, F1])])

    # Test FloatValue '+'
    assert str(f2 + fm3) == str(fm1)
    assert str(f2 + fm3 + fm3 + f2 + f2) == str(f0)
    assert str(f0 + p0) == str(p0)
    assert str(fm3 + p0) == str(S0)
    assert str(fm3 + S1) == str(S2)
    assert str(f3 + F1) == str(SF0)

    # Test FloatValue '-'
    assert str(f2 - fm3) == str(FloatValue(5))
    assert str(f0 - p0) == str(p4)
    assert str(fm3 - p0) == str(S3)
    assert str(fm3 - S1) == str(S4)
    assert str(f3 - F1) == str(SF1)

    # Test FloatValue '*', only need one because all other cases are
    # handled by 'other'
    assert str(f2 * f2) == '%s' % format["float"](4)

    # Test FloatValue '/'
    assert str(fm3 / f2) == str(FloatValue(-1.5))
    assert str(f2 / y) == str(F0)
    assert str(fm3 / p0) == str(F1)
    assert str(fm3 / S1) == str(F2)

    # Silence output
    push_level(CRITICAL)
    with pytest.raises(Exception):
        truediv(f2, F0)
    with pytest.raises(Exception):
        truediv(f2, f0)
    with pytest.raises(Exception):
        truediv(f2, Product([f0, y]))
    pop_level()
Пример #12
0
    def testProductOperators(self):
        "Test binary operators"

        f_0 = format["float"](0)
        f_2 = format["float"](2)
        f_4 = format["float"](4)

        f0 = FloatValue(0.0)
        f1 = FloatValue(1.0)
        f2 = FloatValue(2.0)
        fm1 = FloatValue(-1.0)
        fm3 = FloatValue(-3.0)

        x = Symbol("x", GEO)
        y = Symbol("y", GEO)
        z = Symbol("z", GEO)

        p0 = Product([f2, x])
        p1 = Product([x, y])
        p2 = Product([f2, z])
        p3 = Product([x, y, z])

        S0 = Sum([x, y])
        S1 = Sum([x, z])

        F0 = Fraction(f2, x)
        F1 = Fraction(x, y)
        F2 = Fraction(x, S0)
        F3 = Fraction(x, y)
        F4 = Fraction(p0, y)

        # Test Product '+'
        self.assertEqual(str(p0 + f2), '(%s + %s*x)' % (f_2, f_2))
        self.assertEqual(str(p0 + x), '%s*x' % format["float"](3))
        self.assertEqual(str(p0 + y), '(y + %s*x)' % f_2)
        self.assertEqual(str(p0 + p0), '%s*x' % f_4)
        self.assertEqual(str(p0 + p1), '(%s*x + x*y)' % f_2)
        self.assertEqual(p0 + Product([fm1, x]), x)
        self.assertEqual(Product([fm1, x]) + x, f0)
        self.assertEqual(str(x + Product([fm1, x])), '%s' % f_0)
        self.assertEqual(str(p0 + S0), '(x + y + %s*x)' % f_2)
        self.assertEqual(str(p0 + F3), '(%s*x + x/y)' % f_2)

        # Test Product '-'
        self.assertEqual(str(p0 - f2), '(%s*x-%s)' % (f_2, f_2))
        self.assertEqual(str(p0 - x), 'x')
        self.assertEqual(str(p0 - y), '(%s*x - y)' % f_2)
        self.assertEqual(str(p0 - p0), '%s' % f_0)
        self.assertEqual(str(p0 - p1), '(%s*x - x*y)' % f_2)
        self.assertEqual(str(p0 - S0), '(%s*x - (x + y))' % f_2)
        self.assertEqual(str(p0 - F3), '(%s*x - x/y)' % f_2)

        # Test Product '*', only need to test float, symbol and product.
        # Sum and fraction are handled by 'other'
        self.assertEqual(str(p0 * f0), '%s' % f_0)
        self.assertEqual(str(p0 * fm3), '-%s*x' % format["float"](6))
        self.assertEqual(str(p0 * y), '%s*x*y' % f_2)
        self.assertEqual(str(p0 * p1), '%s*x*x*y' % f_2)

        # Test Product '/'
        self.assertEqual(str(Product([f0, x]) / x), '%s' % f_0)
        self.assertEqual(str(p0 / S0), '%s*x/(x + y)' % f_2)
        self.assertEqual(p1 / y, x)
        self.assertEqual(p1 / p2, Fraction(Product([p1, FloatValue(0.5)]), z))
        self.assertEqual(p1 / z, Fraction(p1, z))
        self.assertEqual(p0 / Product([f2, p1]), Fraction(f1, y))
        self.assertEqual(p1 / p0, Product([FloatValue(0.5), y]))
        self.assertEqual(p1 / p1, f1)
        self.assertEqual(p1 / p3, Fraction(f1, z))
        self.assertEqual(str(p1 / p3), '%s/z' % format["float"](1))
        # Silence output
        push_level(CRITICAL)
        self.assertRaises(Exception, p0.__truediv__, f0)
        self.assertRaises(Exception, p0.__truediv__, F0)
        pop_level()
Пример #13
0
    def testSymbolOperators(self):
        "Test binary operators"

        f_0 = format["float"](0)
        f_1 = format["float"](1)
        f_2 = format["float"](2)
        f_3 = format["float"](3)
        f_0_5 = format["float"](0.5)
        f0 = FloatValue(0.0)
        f2 = FloatValue(2.0)
        fm1 = FloatValue(-1.0)
        fm3 = FloatValue(-3.0)

        x = Symbol("x", GEO)
        y = Symbol("y", GEO)
        z = Symbol("z", GEO)

        p0 = Product([f2, x])
        p1 = Product([x, y])
        p2 = Product([f2, z])
        p3 = Product([y, x, z])

        S0 = Sum([x, y])
        S1 = Sum([x, z])

        F0 = Fraction(f2, y)
        F1 = Fraction(x, y)
        F2 = Fraction(x, S0)
        F3 = Fraction(x, y)
        F4 = Fraction(p0, y)
        F5 = Fraction(fm3, y)

        # Test Symbol '+'
        self.assertEqual(str(x + f2), '(%s + x)' % f_2)
        self.assertEqual(str(x + x), '%s*x' % f_2)
        self.assertEqual(str(x + y), '(x + y)')
        self.assertEqual(str(x + p0), '%s*x' % f_3)
        self.assertEqual(str(x + p1), '(x + x*y)')
        self.assertEqual(str(x + S0), '(x + x + y)')
        self.assertEqual(str(x + F0), '(x + %s/y)' % f_2)

        # Test Symbol '-'
        self.assertEqual(str(x - f2), '(x-%s)' % f_2)
        self.assertEqual(str(x - x), '%s' % f_0)
        self.assertEqual(str(x - y), '(x - y)')
        self.assertEqual(str(x - p0), ' - x')
        self.assertEqual(str(x - p1), '(x - x*y)')
        self.assertEqual(str(x - S0), '(x - (x + y))')
        self.assertEqual(str(x - F5), '(x - -%s/y)' % f_3)

        # Test Symbol '*', only need to test float, symbol and product. Sum and
        # fraction are handled by 'other'
        self.assertEqual(str(x*f2), '%s*x' % f_2)
        self.assertEqual(str(x*y), 'x*y')
        self.assertEqual(str(x*p1), 'x*x*y')

        # Test Symbol '/'
        self.assertEqual(str(x/f2), '%s*x' % f_0_5)
        self.assertEqual(str(x/x), '%s' % f_1)
        self.assertEqual(str(x/y), 'x/y')
        self.assertEqual(str(x/S0), 'x/(x + y)')
        self.assertEqual(str(x/p0), '%s' % f_0_5)
        self.assertEqual(str(y/p1), '%s/x' % f_1)
        self.assertEqual(str(z/p0), '%s*z/x' % f_0_5)
        self.assertEqual(str(z/p1), 'z/(x*y)')
        # Silence output
        push_level(CRITICAL)
        self.assertRaises(Exception, x.__truediv__, F0)
        self.assertRaises(Exception, y.__truediv__, FloatValue(0))
        pop_level()