Exemplo n.º 1
0
 def __init__(self, data: str, ctx: Context):
     self.args = []
     self.is_monomial = False
     self.variables = []
     try:
         self.type, self.value, arg1, arg2 = parse(data)
     except (TypeError):
         input_error_message(data)
         self.type = 'error'
         return
     if self.type == 'symp':
         expr = Expression(self.value, ctx)
         simplify(expr)
         self.__clone(expr)
     elif self.type[0:4] == 'plot':
         expr = Expression(self.value, ctx)
         simplify(expr)
         plot(expr, arg1, arg2, self.type[4], self.type[5])
     elif self.type == 'func':
         for arg in (arg1, arg2):
             self.__get_args(arg, self.value, ctx)
     elif self.type == 'symbol':
         expr = ctx.get_func_from_list(self.value)
         if expr != -1:
             expr = Expression(expr, ctx)
             self.__clone(expr)
         else:
             self.variables.append([self.value, 1])
             self.value = 1
             self.is_monomial = True
     else:
         self.is_monomial = True
Exemplo n.º 2
0
def derive_ui(expr):
    expr = br.transform_brackets(expr)
    util.debug_print("Transformed:\t\t" + expr, 1)
    expr = sim.simplify(expr)
    util.debug_print("Simplified:\t" + expr, 1)
    expr = dev.derive_sub(expr)
    util.debug_print("Derived:\t\t" + expr, 1)
    expr = br.remove_brackets(expr)
    util.debug_print("Removed:\t\t" + expr, 1)
    expr = sim.simplify(expr)
    util.debug_print("Simplified:\t\t" + expr, 1)
    expr = br.back_transform_brackets(expr)
    util.debug_print("Backtransformed:\t" + expr, 1)
    return expr
Exemplo n.º 3
0
def editorValidateExpression(win):
    if win.editor_output == None:
        win.editor_compiletext[3].setText("You have not selected an output node!")
    else:
        try:
            output = editorGenerateExpression(win, win.editor_output)
            win.editor_compiletext[3].setText("")
            popup = createPanel(win, 0, win.height/2-120, win.width, 240)

            # text elements to display the final result
            exp1 = simplify.prettyPrint(output)
            exp2 = simplify.prettyPrint(simplify.simplify(output))
            title1 = createText(win, win.width/2, win.height/2-100, "Generated Expression", 24)
            expression = createText(win, win.width/2, win.height/2-70, exp1, 20)
            copy1 = createButton(win, win.width/2-75, win.height/2-45, 150, 40, "Copy to Clipboard", lambda: copyToClipboard(exp1), "grey")
            title2 = createText(win, win.width/2, win.height/2+20, "Simplified Expression", 24)
            simplified = createText(win, win.width/2, win.height/2+50, exp2, 20)
            copy2 = createButton(win, win.width/2-75, win.height/2+75, 150, 40, "Copy to Clipboard", lambda: copyToClipboard(exp2), "grey")

            close = createButton(win, win.width-50, win.height/2+-120, 50, 30, "X", None, "red")

            close[4] = lambda: undrawElements(win, popup, title1, title2, expression, simplified, copy1, copy2, close)
        except EditorError as e:
            win.editor_compiletext[3].setText(e)
            if e.element:
                e.element[1][3][0].setFill("red")
Exemplo n.º 4
0
 def test_simplification(self):
     for expr in self.expressions_simplify:
         sol = self.expressions_simplify.get(expr)
         expr = br.transform_brackets(expr)
         expr = sim.simplify(expr)
         with self.subTest():
             self.assertEqual(expr, sol)
Exemplo n.º 5
0
def process_data_file(data_file):

    print(data_file)

    # Read geojson from file
    with open(data_file) as json_file:
        geojson = json.load(json_file)

    # Remove duplicate geojson features
    starting_geojson = remove_duplicate_features(geojson)

    simplified_geojson = starting_geojson

    # Count number of features
    number_of_features = count_number_of_features(starting_geojson)
    tolerance = 0.0001

    print('starting # of features', number_of_features)

    # If number of features greater than 100, apply
    # simplify routine
    while number_of_features > 500:

        # Collect lat/lon into an list of dicts
        starting_lon_lat_list = collect_lon_lat_to_list(starting_geojson)

        simplified_lon_lat_list = simplify(starting_lon_lat_list,
                                           tolerance=tolerance,
                                           highestQuality=True)

        # Expand back to geojson feature for each point
        simplified_geojson = create_simplified_geojson(simplified_lon_lat_list,
                                                       starting_geojson)

        number_of_features = count_number_of_features(simplified_geojson)

        if number_of_features < 100:

            # Revert back one to larger number of features
            simplified_geojson = starting_geojson

            number_of_features = count_number_of_features(simplified_geojson)

            break

        else:
            starting_geojson = simplified_geojson
            tolerance = tolerance + 0.0005

    print('ending # of features', number_of_features)

    # Save geojson to file
    output_folder = './output_simplified_jsonld_geojson_ctd_check'

    # get filename of data_file
    filename = Path(data_file).name

    output_file = Path(output_folder, filename)
    with open(output_file, 'w') as f:
        json.dump(simplified_geojson, f)
Exemplo n.º 6
0
def simplify_coordinates(coordinates):

    tolerance = 0.0001
    number_of_coordinates = len(coordinates)

    starting_lon_lat_list = collect_lon_lat_to_list(coordinates)

    while number_of_coordinates > 500:

        # Collect lat/lon into an list of dicts to apply simplify
        # routine to

        simplified_lon_lat_list = simplify(starting_lon_lat_list,
                                           tolerance=tolerance,
                                           highestQuality=True)

        number_of_coordinates = len(simplified_lon_lat_list)

        if number_of_coordinates < 100:

            # Revert back one to larger number of coordinates
            # Use starting_lon_lat_list

            break

        else:
            tolerance = tolerance + 0.00005
            starting_lon_lat_list = simplified_lon_lat_list

    # Convert list of dicts to list of lists for lon/lat
    coordinates = convert_simplified_lon_lat_list(starting_lon_lat_list)

    print('ending # of coordinates', len(coordinates))

    return coordinates
Exemplo n.º 7
0
def splosci(f):
    """
    Splosci (flatten) dano formulo f, kolikor je mozno.
    """
    a = simplify(f)

    def splosci_aux(p):
        """
        Pomozna funkcija za rekurzivne klice.
        """
        if isinstance(p, And):
            nove = []
            for fr in p.formule:
                if isinstance(fr, And):
                    nove += [splosci_aux(x) for x in fr.formule]
                else:
                    nove.append(splosci_aux(fr))
            p.formule = nove
        elif isinstance(p, Or):
            nove = []
            for fr in p.formule:
                if isinstance(fr, Or):
                    nove += [splosci_aux(x) for x in fr.formule]
                else:
                    nove.append(splosci_aux(fr))
            p.formule = nove
        else:
            return p
        return p

    return splosci_aux(a)
Exemplo n.º 8
0
 def _test_GivenStrings(self):
     self.assertEqual("x**2-1", simplify("(x-1)*(x+1)"))
     self.assertEqual("x**2+2*x+1", simplify("(x+1)*(x+1)"))
     self.assertEqual("x**2+6*x", simplify("(x+3)*x*2-x*x"))
     self.assertEqual("x**3+x**2+x", simplify("x+x*x+x*x*x"))
     self.assertEqual("x**4+3*x+6", simplify("(2*x+3)*2-x+x*x*x*x"))
     self.assertEqual("0", simplify("x*x-(x-1)*(x+1)-1"))
     self.assertEqual("-x", simplify("5-5-x"))
     self.assertEqual("-1", simplify("x*x*x-x*x*x-1"))
Exemplo n.º 9
0
 def _test_GivenStrings(self):
     self.assertEqual("x**2-1", simplify("(x-1)*(x+1)"))
     self.assertEqual("x**2+2*x+1", simplify("(x+1)*(x+1)"))
     self.assertEqual("x**2+6*x", simplify("(x+3)*x*2-x*x"))
     self.assertEqual("x**3+x**2+x", simplify("x+x*x+x*x*x"))
     self.assertEqual("x**4+3*x+6", simplify("(2*x+3)*2-x+x*x*x*x"))
     self.assertEqual("0", simplify("x*x-(x-1)*(x+1)-1"))
     self.assertEqual( "-x", simplify("5-5-x"))
     self.assertEqual("-1", simplify("x*x*x-x*x*x-1"))
Exemplo n.º 10
0
def solve(heuristic, file):
    start = time.time()
    heuristics = {0: "Random", 1: "Jeroslaw", 2: "MOMs"}

    print("Solving using {} heuristic".format(heuristics[int(heuristic)]))

    which_method = int(heuristic)

    # List for data analysis EXCEL
    # [#unit_clauses, %of reduction from first simplify, #splits, #backtrackings, #time]
    results = [0, 0, 100., 0, 0, 0]
    split_count = 0
    back_track_count = 0
    problem_start_time = time.time()
    rules = read_files.read_DIMACS_file(file)
    rules, literals_dict, truth_values = read_files.init_database(rules)
    results[1] = len(truth_values)
    old_clauses_count = len(rules)
    done = False
    rules_before_split, literals_dict_before_split, truth_values_before_split = {}, {}, {}
    split_choice, neg_literal = [], []

    while done == False:
        back_track = False
        # Simplify
        rules, literals_dict, truth_values, split_choice, neg_literal, \
        rules_before_split, literals_dict_before_split, truth_values_before_split, back_track = \
            simplify.simplify(rules, literals_dict, truth_values, split_choice, neg_literal,
                              rules_before_split, literals_dict_before_split, truth_values_before_split, back_track)
        new_clauses_count = len(rules)
        if split_count > 2000:
            break

        if back_track:
            back_track_count += 1

        if new_clauses_count == 0:
            pretty_print.solution(truth_values)
            results[3] = split_count
            results[4] = back_track_count
            results[5] = float("{0:.2f}".format(time.time() -
                                                problem_start_time))
            print("Solved in {0:.2f}s".format(time.time() -
                                              problem_start_time))
            print("# splits {}".format(split_count))
            done = True

            with open("{}.out".format(file), 'w') as f:
                for truth in truth_values:
                    f.write("{} 0\n".format(truth))

        elif old_clauses_count == new_clauses_count and back_track == False:
            split_count += 1
            # Split
            rules, literals_dict, truth_values, split_choice, neg_literal, \
            rules_before_split, literals_dict_before_split, truth_values_before_split = \
                split.split(rules, literals_dict, truth_values, split_choice, neg_literal,
                            rules_before_split, literals_dict_before_split, truth_values_before_split, which_method)
        old_clauses_count = new_clauses_count
Exemplo n.º 11
0
def solve(heuristic, file):
    start = time.time()
    heuristics = {1: "Basic DPLL -- Random", 2: "Jeroslow-Wang", 3: "MOMs"}
    print('')
    print('=============== SAT Solver ================')
    print("Solving using {} heuristic".format(heuristics[int(heuristic)]))
    print('...\n')

    which_method = int(heuristic)

    rules = read_files.read_DIMACS_file(file)
    rules, literals_dict, truth_values = read_files.init_database(rules)
    rules_before_split, literals_dict_before_split, truth_values_before_split = {}, {}, {}
    split_choice, neg_literal = [], []
    old_clauses_count = len(rules)
    back_track_count = 0
    split_count = 0
    done = False
    problem_start_time = time.time()

    while done == False:
        back_track = False
        # Simplify
        rules, literals_dict, truth_values, split_choice, neg_literal, \
        rules_before_split, literals_dict_before_split, truth_values_before_split, back_track, file = \
            simplify.simplify(rules, literals_dict, truth_values, split_choice, neg_literal,
                              rules_before_split, literals_dict_before_split, truth_values_before_split, back_track, file)
        new_clauses_count = len(rules)
        if back_track:
            back_track_count += 1

        if new_clauses_count == 0:

            print('The problem has a solution -- SAT')
            print("Solved in {0:.2f}s".format(time.time() -
                                              problem_start_time))
            print("Number of splits: {}".format(split_count))
            print("Number of backtracks: {}".format(back_track_count))
            print('The solution can be found at the file: {}.out'.format(
                str(file)))
            print('')
            done = True
            with open("{}.out".format(file), 'w') as f:
                f.write("p cnf {} {}\n".format(len(truth_values),
                                               len(truth_values)))
                for truth in truth_values:
                    f.write("{} 0\n".format(truth))

        elif old_clauses_count == new_clauses_count and back_track == False:
            split_count += 1
            # Split
            rules, literals_dict, truth_values, split_choice, neg_literal, \
            rules_before_split, literals_dict_before_split, truth_values_before_split = \
                split.split(rules, literals_dict, truth_values, split_choice, neg_literal,
                            rules_before_split, literals_dict_before_split, truth_values_before_split, which_method)
        old_clauses_count = new_clauses_count
Exemplo n.º 12
0
def main():
    print("Boolean Algebra Utility")
    print("Commands: 'table', 'eval', 'same', 'simplify', 'ui' and 'quit'")
    print("TO USE THE CIRCUIT UI, TYPE 'ui'")
    print("TO END THE PROGRAM, TYPE 'quit'")
    while True:
        command = input("\n[COMMAND] > ")

        if command.lower() in ["table", "truth", "truthtable"]:
            print(
                "\nEnter the boolean expression to generate a truth table for it."
            )
            expression = generateExpressionErrorless(input("[BOOLEAN] > "))
            calcTruthTable(expression)

        elif command.lower() in [
                "eval", "evaluate", "calc", "calculate", "calcvalue"
        ]:
            print("\nEnter the boolean expression to get the output of.")
            expression = generateExpressionErrorless(input("[BOOLEAN] > "))
            print("OUTPUT = {}".format(calcValue(expression)))

        elif command.lower() in ["equiv", "equivalent", "same", "compare"]:
            print("\nEnter the 2 boolean expressions to comapre.")
            expression1 = generateExpressionErrorless(input("[BOOLEAN #1] > "))
            expression2 = generateExpressionErrorless(input("[BOOLEAN #2] > "))
            print(
                isEquivalent(expression1, expression2)
                and "The 2 expressions are equivalent"
                or "The 2 expressions are not equivalent")

        elif command.lower() in ["simplify", "simple"]:
            print("\nEnter the expression to simplify.")
            expression = removeBrackets(
                generateExpressionErrorless(input("[BOOLEAN] > ")))
            print("SIMPLIFIED = {}".format(
                simplify.prettyPrint(simplify.simplify(expression))))
            print(
                "NOTE: Letters may not be in alphabetical order, but should be correct due to the Commutative Law."
            )

        elif command.lower() in ["ui", "builder", "creator"]:
            print("UI Launching...")
            print("Check your taskbar for a window called 'Circuit Builder'")
            ui.createEditor()

        elif command.lower() in ["stop", "quit", "close", "end", "leave"]:
            print("\nQuitting...")
            break

        else:
            print("Unknown Command")
            print(
                "Commands: 'table', 'eval', 'same', 'simplify', 'ui' and 'quit'"
            )
Exemplo n.º 13
0
 def test_GivenExpressions(self):
     #"(x-1)*(x+1)"
     self.assertEqual("x**2-1", p(s(x(1), c(-1)), s(x(1), c(1))).simplify().fmt())
     self.assertEqual("x**2+2*x+1", simplify("(x+1)*(x+1)"))
     self.assertEqual("x**2+6*x", simplify("(x+3)*x*2-x*x"))
     self.assertEqual("x**3+x**2+x", simplify("x+x*x+x*x*x"))
     self.assertEqual("x**4+3*x+6", simplify("(2*x+3)*2-x+x*x*x*x"))
     self.assertEqual("0", simplify("x*x-(x-1)*(x+1)-1"))
     self.assertEqual( "-x", simplify("5-5-x"))
     self.assertEqual("-1", simplify("x*x*x-x*x*x-1"))
Exemplo n.º 14
0
 def run(self):
     while True:
         inp = self.input_method()
         inp_strip = inp.strip()
         if inp_strip[0] == '@':
             inp_split = inp_strip[1:].split()
             order = OrderToken(inp_split, self.keywords)
             if order.value == 'exit':
                 break
         else:
             self.raw_calc_input.append(inp)
             self.processed_calc_input.append(self.preprocess(inp))
             self.calc_output.append(simplify(calcparser.parse(self.processed_calc_input[-1])))
Exemplo n.º 15
0
 def test_GivenExpressions(self):
     #"(x-1)*(x+1)"
     self.assertEqual("x**2-1",
                      p(s(x(1), c(-1)), s(x(1), c(1))).simplify().fmt())
     self.assertEqual("x**2+2*x+1", simplify("(x+1)*(x+1)"))
     self.assertEqual("x**2+6*x", simplify("(x+3)*x*2-x*x"))
     self.assertEqual("x**3+x**2+x", simplify("x+x*x+x*x*x"))
     self.assertEqual("x**4+3*x+6", simplify("(2*x+3)*2-x+x*x*x*x"))
     self.assertEqual("0", simplify("x*x-(x-1)*(x+1)-1"))
     self.assertEqual("-x", simplify("5-5-x"))
     self.assertEqual("-1", simplify("x*x*x-x*x*x-1"))
Exemplo n.º 16
0
def start_cube():
    c = Cube(3)
    s = Solution(c)
    possible_steps = [
        'D', 'd', 'U', 'u', 'L', 'l', 'R', 'r', 'B', 'b', 'F', 'f'
    ]

    print("Hello! Here is the program to help you with solving Rubik's Cube.")
    print(
        "Do you want to shuffle cube yourself, or perform autoshuffle? (enter 'my' for your shuffle or enter 'auto' for shuffle)"
    )
    shuffle_type = str(input())
    shuffle_type = shuffle_type.strip().lower()

    if shuffle_type == "my":
        print(
            "Enter steps you want to make seperated by spaces (possible steps: D, d, U, u, L, l, R, r, B, b, F, f)"
        )
        shuffle_steps_str = str(input())
        shuffle_steps = shuffle_steps_str.split()
        for i in shuffle_steps:
            if i not in possible_steps:
                print("Invalid input! No such steps allowed")
                return 1
        s.shuffle_user(shuffle_steps)
    elif shuffle_type == "auto":
        print(
            "Enter numeric value of seed which is used to generate random steps"
        )
        try:
            shuffle_seed = int(input())
        except:
            print("Invalid input! Try again")
            return 1
        s.shuffle(shuffle_seed)
        print("Used steps to shuffle the cube:")
        print(s.shuffle_steps)
    else:
        print("Invalid input! Try again")
        return 1

    s.solve_cube()
    # vidualizatsia
    result_steps = s.result_steps
    for i in range(3):
        result_steps = simplify(result_steps)

    print("Steps to solve a cube:")
    print(result_steps)

    return s.shuffle_steps, result_steps
Exemplo n.º 17
0
def decomposePolynomial( polynomial ):
    ret = []
    if isinstance( polynomial, astPlus ):
        return decomposePolynomial( polynomial.left ) + decomposePolynomial( polynomial.right )
    elif isinstance( polynomial, astMinus ):
        if isinstance( polynomial.right, astUminus ):
            return decomposePolynomial( polynomial.left ) + decomposePolynomial( polynomial.right.arg )
        return decomposePolynomial( polynomial.left ) + decomposePolynomial( simplify.simplify( -polynomial.right ) )
    else:
        # it is a monomial
        if isinstance( polynomial, astUminus ):
            return [ ( MINUS, polynomial.arg ) ]
        else:
            return [ ( PLUS, polynomial ) ]
Exemplo n.º 18
0
    def parts(u, dv):
        
        du = derivatives.main(u)
        v = antiderivative(dv, variable, limit)

        ddu = derivatives.main(du)
        ddv = derivatives.main(dv)

        if func in (BinaryOp(left = ddu, op = '⋅', right = dv), BinaryOp(left = dv, op = '⋅', right = ddu)):
            return BinaryOp(
                left = BinaryOp(
                    left = BinaryOp(
                        left = u,
                        op = '⋅',
                        right = v
                    ),
                    op = '-',
                    right = BinaryOp(
                        left = du,
                        op = '⋅',
                        right = dv
                    )
                ),
                op = '÷',
                right = Constant(2)
            )
                    
        vdu = simplify.simplify(
            antiderivative(
                BinaryOp(
                    left = du,
                    op = '⋅',
                    right = v
                ),
                variable,
                limit
            )
        )

        return BinaryOp(
            left = BinaryOp(
                left = u,
                op = '⋅',
                right = v
            ),
            op = '-',
            right = vdu
        )
Exemplo n.º 19
0
def load():
    data = None
    with open(sys.argv[1], 'r') as in_file:
        data = geojson.loads(in_file.read())

    cluster = Cluster()
    session = cluster.connect('global')
    level = 16

    ins_statement = session.prepare(
        '''INSERT INTO slave (level, s2_id, time, osm_id, json)
					VALUES (?, ?, ?, ?, ?)''')

    s = Set()
    for feature in data['features']:
        osm_id = feature['id']
        json = geojson.dumps(feature)

        featuretype = feature['geometry']['type']
        featurecoord = feature['geometry']['coordinates']

        # A list of every lon,lat pairs a feature has
        ptlist = []

        if (featuretype == "Point"):
            ptlist = case1(featurecoord)
        if (featuretype == "LineString" or featuretype == "MultiPoint"):
            ptlist = case2(featurecoord)
        if (featuretype == "Polygon" or featuretype == "MultiLineString"):
            ptlist = case3(featurecoord)
        if (featuretype == "MultiPolygon"):
            ptlist = case4(featurecoord)

        # Set to track distinct S2 values
        s2set = Set()
        # 16242 without simp
        sptlist = simplify(ptlist, 0.01, True)
        for pt in ptlist:
            latlng = s2sphere.LatLng.from_degrees(pt[1], pt[0])
            cell = s2sphere.CellId.from_lat_lng(latlng).parent(level)
            s2set.add(ctypes.c_long(cell.id()).value)

        for s2 in s2set:
            session.execute(ins_statement,
                            (level, s2, uuid.uuid1(), osm_id, json))

    cluster.shutdown()
Exemplo n.º 20
0
def simplify_lon_lat_list(lon_lat_list):

    # convert to numeric and apply simplify routine
    lon_lat_list = np.array(lon_lat_list, dtype=np.float32)

    lon_lat_list = np.array(lon_lat_list).tolist()

    tolerance = 0.5
    highQuality = True

    lon_lat_list = simplify.simplify(lon_lat_list, tolerance, highQuality)

    # Convert back to strings
    lon_lat_list = np.array(lon_lat_list)
    lon_lat_list = lon_lat_list.astype(str)
    lon_lat_list = lon_lat_list.tolist()

    return lon_lat_list
Exemplo n.º 21
0
def unifyPolynomialMonomials( a, b ):
    """Take two monomials of a polynomial and attempt to unify them.

    Return values can be:
    * None, if no unification is possible
    * A single astNode instance, if the two factors have been successfully unified
    * A list of astNodes if the unification yielded multiple terms (e.g. by expansion)
    """
    # minuses have been pulled out by the polynomial decomposer
    assert( not isinstance( a, astUminus ) )
    assert( not isinstance( b, astUminus ) )

    ( s, p ) = a
    ( t, q ) = b

    if isinstance( p, astConst ) and p.const == 0:
        return b
    if isinstance( q, astConst ) and q.const == 0:
        return a
    if isinstance( p, astConst ) and isinstance( q, astConst ):
        if s == t:
            return ( s, astConst( p.const + q.const ) )
        if p.const > q.const:
            return ( s, astConst( p.const - q.const ) )
        return ( t, astConst( q.const - p.const ) )
    if isinstance( p, astTimes ) and isinstance( p.left, astConst ) \
       and isinstance( q, astTimes ) and isinstance( q.left, astConst ) \
       and p.right == q.right:
        # n * a + m * a = (n + m) * a
        ( sign, factor ) = unifyPolynomialMonomials( ( s, p.left ), ( t, q.left ) )
        return ( sign, simplify.simplify( factor * p.right ) )
    if isinstance( p, astTimes ) and isinstance( p.left, astConst ) \
       and q == p.right:
        # n * a + 1 * a = (n + 1) * a
        return unifyPolynomialMonomials( a, ( t, astConst( 1 ) * q ) )
    if isinstance( q, astTimes ) and isinstance( q.left, astConst ) \
       and p == q.right:
        # 1 * a + n * a = (n + 1) * a
        return unifyPolynomialMonomials( ( s, astConst( 1 ) * p ), b )
    if p == q:
        # a + a = 2a
        return unifyPolynomialMonomials( ( s, astConst( 1 ) * p ), ( t, astConst( 1 ) * q ) )
    return None
Exemplo n.º 22
0
def simplifyMonomial(monomial):
    (sign, parts) = decomposeMonomial(monomial)
    # print( "Decomposed monomial %s into:" % monomial )
    # print( sign )
    # print( parts )
    unificationNeeded = True
    while unificationNeeded:
        unificationNeeded = False
        for i, parti in enumerate(parts):
            for j, partj in enumerate(parts[i + 1 :]):
                res = unifyMonomialFactors(parti, partj)
                if res is not None:
                    # we found a possible unification between two factors
                    # parti and partj
                    # combine them, remove the original parts and
                    # restart unification from scratch
                    unificationNeeded = True
                    del parts[j + i + 1]
                    del parts[i]
                    if isinstance(res, astNode):
                        parts.append(res)
                    else:
                        # parts is a list
                        parts += res
                    break
            if unificationNeeded:
                break
    parts.sort()
    expr = composeMonomial(parts)
    if sign == MINUS:
        res = astUminus(expr)
    else:
        res = expr
    if monomial != res:
        # may need to re-apply simplification
        # until we reach a fixed point
        # if, for example, the monomial simplification
        # yielded a polynomial through distributivity of multiplication
        return simplify.simplify(res)
    # we've reached a fixes point
    return res
Exemplo n.º 23
0
def transform(formula, output):
    """
    :param formula: String representation of a modal formula.
    The syntax for such a formula is per the grammar as stipulated in the README.
    Example input: "(a|b) & (~c => d)"
    :param output: boolean value.

    :return: if output is true, prints modal clausal form (mcf) of transformed formula.
    Otherwise returns mcf as dictionary.
    """
    try:
        modal_clause = clausify.clausify(simplify.simplify(nnf.to_nnf(parser.parse(formula))))  # type: dictionary

        if output:
            print(clausify.to_string(modal_clause))
        else:
            return modal_clause
            
    except RuntimeError as re:
        print('Unable to form modal clause: {}'.format(re.args[0]))
        raise SystemExit(1)
Exemplo n.º 24
0
 def convert_to_cnf_aux(f):
     """
     Prevede funkcijo v CNF obliko.
     Kot vhod prejme funkcijo. Funkcija mora biti v primerni obliki (negacije
     so lahko le pred spremenljivkami).
     """
     if isinstance(f, (V, Not, Tru, Fls)):
         return f
     if isinstance(f, And):
         combined = []   # Ze v cnf obliki, samo zdruzimo skupaj posamezne konjunkcije.
         for p in f.formule:
             combined.append(convert_to_cnf_aux(p))
         return simplify(And(combined))
     if isinstance(f, Or):
         combined = []   # Moramo pretvoriti v CNF.
         for p in f.formule:
             combined.append(convert_to_cnf_aux(p))
         # Pretvorimo tako, da naredimo vse mozne kombinacije med konjunkcijo in disjunkcijo.
         combined = kombinacije(combined)
         comb2 = []
         for p in combined:
             comb2.append(Or(p))
         return And(comb2)
Exemplo n.º 25
0
def main(options):
    result = {}
    with open(options.training_file, "r") as training_data_file:
        training_data = training_data_file.read()
    training_data = json.loads(training_data)
    language = training_data["language"]
    letters = training_data["data"]
    training_data_dir = os.path.dirname(os.path.realpath(
        options.training_file))
    print("Language %s(%s)" % (language["name"], language["code"]))
    for letter in letters:
        # print("Letter %s" % (letter["letter"]))
        samples = []
        for sample_file_name in letter["samples"]:
            sample_file = os.path.join(training_data_dir, sample_file_name)
            strokes = extract_strokes(sample_file)
            simplifiedStrokes = [
                simplify.simplify(stroke, 3, True) for stroke in strokes
            ]
            # print("\t%s" % (sample_file_name))
            samples.append({"strokes": simplifiedStrokes})
        result[letter["letter"]] = {"samples": samples}
    return result
Exemplo n.º 26
0
def test_exponential_exponential(capsys):
    abstract_syntax_tree = "3^3^2"
    expected = 3**9
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 27
0
def test_solver_mult_combine_symbols():
    assert test_generator(simplify('x * x')) == E('x', 2)
    assert test_generator(simplify('3 * x * y * 3 * y / (4 * y * x)')) == F(M(9, S('y')), 4)
Exemplo n.º 28
0
def test_exp():
    assert test_generator(simplify('3 ^ 4')) == 81
    assert test_generator(simplify('(x ^ 4) ^ 3')) == E('x', 12)
    assert test_generator(simplify('(x / y) ^ 2')) == F(E('x', 2), E('y', 2))
    assert test_generator(simplify('(x * y) ^ 2')) == M(E('x', 2), E('y', 2))
Exemplo n.º 29
0
def test_division(capsys):
    abstract_syntax_tree = ("DIVIDE", ("DIVIDE", 50, 10), 5)
    expected = 1
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 30
0
def test_subtraction_subtraction(capsys):
    abstract_syntax_tree = ("MINUS",  ("MINUS", 4, 3), 10)
    expected = -11
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 31
0
def antiderivative(func, variable = 'x', limit = 1 << 12):
    
    def parts(u, dv):
        
        du = derivatives.main(u)
        v = antiderivative(dv, variable, limit)

        ddu = derivatives.main(du)
        ddv = derivatives.main(dv)

        if func in (BinaryOp(left = ddu, op = '⋅', right = dv), BinaryOp(left = dv, op = '⋅', right = ddu)):
            return BinaryOp(
                left = BinaryOp(
                    left = BinaryOp(
                        left = u,
                        op = '⋅',
                        right = v
                    ),
                    op = '-',
                    right = BinaryOp(
                        left = du,
                        op = '⋅',
                        right = dv
                    )
                ),
                op = '÷',
                right = Constant(2)
            )
                    
        vdu = simplify.simplify(
            antiderivative(
                BinaryOp(
                    left = du,
                    op = '⋅',
                    right = v
                ),
                variable,
                limit
            )
        )

        return BinaryOp(
            left = BinaryOp(
                left = u,
                op = '⋅',
                right = v
            ),
            op = '-',
            right = vdu
        )

    if not limit:
        raise Exception('Unable to find antiderivative in time')
    limit -= 1

    if isinstance(func, str):
        if func in standard_integrals:
            return standard_integrals[func]
        
        func = mathparser.parse(func)
        
    if func in derivatives.standard_derivatives.values():
        for key, value in derivatives.standard_derivatives.items():
            if value == func:
                return mathparser.parse(key + '({})'.format(variable))
            
    if isinstance(func, Constant):
        Ifunc = mathparser.parse('{}{}'.format(func.value, variable))

    if isinstance(func, Variable):
        if is_x(func, variable):
            Ifunc = mathparser.parse('{}²÷2'.format(variable))
        else:
            Ifunc = mathparser.parse('{}{}'.format(func.name, variable))

    if isinstance(func, UnaryOp):

        if func.pos == 'Prefix':

            if func.op in standard_integrals and is_x(func.operand, variable):
                return nest(standard_integrals[func.op], Variable(variable), 'x')
            
            if is_axb(func.operand, variable):
                if func.op in '√∛':
                    # Power rule with fractional powers
                    # ∫(ax+b)ⁿ dx = ∫uⁿ du÷a, u = ax+b, du = a dx
                    #             = u*(n+1)÷(a(n+1))
                    #             = (ax+b)*(n+1) ÷ (a(n+1))

                    f = func.operand
                    n = 1 / ('√∛'.index(func.op) + 2)
                    a = derivatives.main(f).value

                    Ifunc = BinaryOp(
                        left = BinaryOp(
                            left = f,
                            op = '*',
                            right = Constant(n+1)
                        ),
                        op = '÷',
                        right = Constant(a*(n+1))
                    )

                else:
                    # Basic u-substitution
                    # ∫f(ax+b) dx = ∫f(u) du÷a, u = ax+b, du = a dx
                    
                    fu = UnaryOp('Prefix', op = func.op, operand = Variable('u'))
                    Ifu = nest(antiderivative(fu, 'u', limit), Variable(variable), 'u')
                    a = derivatives.main(func.operand)

                    Ifunc = BinaryOp(
                        left = nest(Ifu, func.operand, variable),
                        op = '÷',
                        right = a
                    )

            if func.op == '-':
                return UnaryOp('Prefix', op = '-', operand = antiderivative(func.operand))

        if func.pos == 'Postfix':

            if derivatives.REGEX['exponent'].search(func.op):
                n = mathparser.normalise(func.op)
                f = func.operand

                if is_axb(f, variable):
                    # Power rule
                    # ∫(ax+b)ⁿ dx = ∫uⁿ du÷a, u = ax+b, du = a dx
                    #             = u*(n+1)÷(a(n+1))
                    #             = (ax+b)*(n+1) ÷ (a(n+1))

                    a = derivatives.main(f).value
                    
                    Ifunc = BinaryOp(
                        left = BinaryOp(
                            left = f,
                            op = '*',
                            right = Constant(n+1)
                        ),
                        op = '÷',
                        right = Constant(a*(n+1))
                    )

                else:
                    # Generalised power rule
                    # ∫f(x)ⁿ dx
                    
                    if is_trig(f):
                        # Integration by reduction formula

                        if is_x(f.operand, variable):
                            Ifunc = reduce_trig(f, n, variable, limit)
                            
                        elif is_axb(f.operand, variable):
                            fu = UnaryOp('Prefix', op = f.op, operand = Variable('u'))
                            Ifu = nest(antiderivative(fu, 'u', limit), Variable(variable), 'u')
                            a = derivatives.main(func.operand)

                            Ifunc = BinaryOp(
                                left = nest(Ifu, func.operand, variable),
                                op = '÷',
                                right = a
                            )
                            

    if isinstance(func, BinaryOp):
        f = func.left
        op = func.op
        g = func.right
            
        df = derivatives.main(f)
        dg = derivatives.main(g)

        if op in '+-':
            # Addition rule
            # ∫f(x)±g(x) dx = ∫f(x) dx ± ∫g(x) dx

            If = antiderivative(f, variable, limit = limit)
            Ig = antiderivative(g, variable, limit = limit)

            Ifunc = BinaryOp(
                left = If,
                op = op,
                right = Ig
            )

        if op == '⋅':
            
            if isinstance(f, Constant):
                # Constant product rule
                # ∫af(x) dx = a∫f(x) dx
                
                Ig = antiderivative(g, variable, limit = limit)

                Ifunc = BinaryOp(
                    left = f,
                    op = '⋅',
                    right = Ig
                )

            elif inspect(func, f, g, variable) or inspect(func, g, f, variable):
                # Integration by inspection
                # ∫f'(g(x))g'(x) dx = f(g(x))

                if inspect(func, g, f, variable):
                    df, dg = g, f
                else:
                    df, dg = f, g

                f = antiderivative(
                    UnaryOp(
                        df.pos,
                        op = df.op,
                        operand = Variable('u')
                    ),
                    'u', limit)
                
                g = df.operand
                d_g = derivatives.main(g)

                consts = []

                while dg != d_g and is_const_prod(dg, d_g):
                    if isinstance(d_g.left, Constant):
                        consts.append(d_g.left.value)
                        d_g = d_g.right

                prod = 1
                for v in consts:
                    prod *= v
                prod = Constant(1/prod)

                Ifunc = BinaryOp(
                    left = prod,
                    op = '⋅',
                    right = nest(f, g, 'u')
                )

            elif is_power(f) and is_power(g):
                if is_trig(f.operand) and is_trig(g.operand):
                    m = mathparser.normalise(f.op)
                    n = mathparser.normalise(g.op)
                    f = f.operand
                    g = g.operand
                    
                if is_trig(f.left) and is_trig(g.left):
                    m = f.right.value
                    n = g.right.value
                    f = f.left
                    g = g.left
                    
                # Product of exponentiated trig
                # ∫f(x)ᵐ⋅g(x)ⁿ dx

                if is_x(f.operand, variable) and is_x(g.operand, variable):
                    Ifunc = reduce_trig_prod(f, g, m, n, 1, 0, variable, limit)

                elif is_ax(f.operand, variable) and is_ax(g.operand, variable) and f.operand == g.operand:
                    a = f.operand.left.value
                    Ifunc = reduce_trig_prod(f, g, m, n, a, 0, variable, limit)

                elif is_axb(f.operand, variable) and is_axb(g.operand, variable) and f.operand == g.operand:
                    if isinstance(f.operand.right, Constant):
                        a = f.operand.left.left.value
                        b = f.operand.right.value
                    else:
                        a = f.operand.right.left.value
                        b = f.operand.left.value
                    Ifunc = reduce_trig_prod(f, g, m, n, a, b, variable, limit)

            else:
                # Integration by parts
                # ∫u dv = uv - ∫v du
                # ∫f(x)g(x) dx = f(x)∫g(x) dx - ∫(∫g(x) dx)f'(x) dx

                try:
                    Ifunc = parts(f, g)
                except:
                    Ifunc = parts(g, f)

        if op == '*':

            if is_axb(f, variable) and isinstance(g, Constant):
                if g.value != -1:
                    # Power rule
                    # ∫(ax+b)ⁿ dx = ∫uⁿ du÷a, u = ax+b, du = a dx
                    #             = u*(n+1)÷(a(n+1))
                    #             = (ax+b)*(n+1) ÷ (a(n+1))
                    
                    a = df.value
                    n = g.value
                    
                    Ifunc = BinaryOp(
                        left = BinaryOp(
                            left = f,
                            op = '*',
                            right = Constant(n+1)
                        ),
                        op = '÷',
                        right = Constant(a*(n+1))
                    )

                if g.value == -1:
                    # Log rule
                    # ∫(ax+b)⁻¹ dx = ∫u⁻¹ du÷a, u = ax+b, du = a dx
                    #              = ln(u)÷a
                    #              = ln(ax+b)÷a
                    
                    a = df
                    
                    Ifunc = BinaryOp(
                        left = UnaryOp(
                            'Prefix',
                            op = 'ln',
                            operand = f
                        ),
                        op = '÷',
                        right = a
                    )

            if isinstance(f, Constant) and is_axb(g, variable):
                # Exponential rule
                # ∫c*(ax+b) dx = c*b∫c*(ax) dx
                #              = (c*(ax+b)) ÷ (aln(c))
                
                a = dg
                c = f
                
                Ifunc = BinaryOp(
                    left = func,
                    op = '÷',
                    right = BinaryOp(
                        left = a,
                        op = '⋅',
                        right = UnaryOp(
                            'Prefix',
                            op = 'ln',
                            operand = c
                        )
                    )
                )

            if is_trig(f) and isinstance(g, Constant):
                # Integration by reduction formula

                n = g.value

                if is_x(f.operand, variable):
                    Ifunc = reduce_trig(f, n, variable, limit)
                    
                elif is_axb(f.operand, variable):
                    fu = UnaryOp('Prefix', op = f.op, operand = Variable('u'))
                    Ifu = nest(antiderivative(fu, 'u', limit), Variable(variable), 'u')
                    a = derivatives.main(func.operand)

                    Ifunc = BinaryOp(
                        left = nest(Ifu, func.operand, variable),
                        op = '÷',
                        right = a
                    )

        if op == '÷':

            if isinstance(simplify.simplify(f), Constant):
                f = simplify.simplify(f)

            if isinstance(simplify.simplify(g), Constant):
                g = simplify.simplify(g)

            if isinstance(f, Constant):
                if (
                    isinstance(g, UnaryOp)  and \
                    g.pos == 'Postfix'      and \
                    derivatives.REGEX['exponent'].search(g.op)
                ) or (
                    isinstance(g, UnaryOp)  and \
                    g.pos == 'Prefix'       and \
                    g.op in '√∛'
                ):
                    # ∫c÷f(x)ⁿ dx = ∫cf(x)⁻ⁿ
                    
                    if g.pos == 'Postfix':
                        n = mathparser.normalise(g.op)
                    else:
                        n = 1 / ('√∛'.index(g.op) + 2)
                        
                    if is_axb(g.operand, variable):
                        # ∫c÷(ax+b)ⁿ dx
                        
                        if n != -1:
                            # Power rule with negative power
                            # ∫c÷(ax+b)ⁿ dx = c∫(ax+b)⁻ⁿ dx
                            #               = c(ax+b)*(1-n) ÷ (a(1-n))
                            
                            a = derivatives.main(g.operand).value
                            
                            Ifunc = BinaryOp(
                                left = f,
                                op = '⋅',
                                right = BinaryOp(
                                    left = BinaryOp(
                                        left = g.operand,
                                        op = '*',
                                        right = Constant(1-n)
                                    ),
                                    op = '÷',
                                    right = Constant(a*(1-n))
                                )
                            )

                        if n == -1:
                            # Log rule
                            # ∫c÷(ax+b) dx = c∫1÷(ax+b) dx
                            #              = cln(ax+b)÷a
                            
                            a = derivatives.main(g.operand)

                            Ifunc = BinaryOp(
                                left = f,
                                op = '⋅',
                                right = BinaryOp(
                                    left = UnaryOp(
                                        'Prefix',
                                        op = 'ln',
                                        operand = g.operand
                                    ),
                                    op = '÷',
                                    right = a
                                )
                            )

                if is_axb(g, variable):
                    # ∫c÷(ax+b) dx = c∫1÷(ax+b) dx
                    #              = cln(ax+b)÷a
                    
                    a = dg

                    Ifunc = BinaryOp(
                        left = f,
                        op = '⋅',
                        right = BinaryOp(
                            left = UnaryOp(
                                'Prefix',
                                op = 'ln',
                                operand = g
                            ),
                            op = '÷',
                            right = a
                        )
                    )

            if isinstance(g, Constant):
                # ∫f(x)÷a dx = ∫f(x) dx÷a

                Ifunc = BinaryOp(
                    left = simplify.simplify(antiderivative(
                        f,
                        variable,
                        limit
                    )),
                    op = '÷',
                    right = g
                )

            if is_poly(f, variable) and is_poly(g, variable):
                print('>', f, g)

    try:
        return Ifunc
    except:
        raise Exception('Unable to find antiderivative')
Exemplo n.º 32
0
def test_factorial_factorial(capsys):
    abstract_syntax_tree = "4!!"
    expected = factorial(factorial(4))
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 33
0
def test_addition(capsys):
    abstract_syntax_tree = ('PLUS', 3, 4)
    expected = 7
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 34
0
def test_factorial_parenthesis(capsys):
    abstract_syntax_tree = "(2 + 1)!"
    expected = 6
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 35
0
    pimg = Image.frombytes('F', (w, h), fimg.tostring(), 'raw', 'F;32NF')

    pimg.save(args.file + ".tif")

    hmin = e1 * (1 - imin) + e2 * imin
    hmax = e1 * (1 - imax) + e2 * imax

    contours = []
    hstep = 2.5
    nc = m.ceil((hmax - hmin) / hstep)
    for i in range(nc):
        hgt = imin + i * hstep / (hmax - hmin)
        npc = measure.find_contours(img, hgt)
        cs = []
        for c in npc:
            c = simplify(c, 5, True)
            cs.append(c)
        cs = np.array(cs)
        contours.append(cs)
    np.savez_compressed(args.file + "-contours", *contours)

    #     mi,ma = float(np.amin(img)),float(np.amax(img))
    #     print("contour",mi,ma)
    #     for i in range(50):
    #       d = float(mi*(1-i/50)+ma*i/50)
    #       print("contour",d)
    #       npc = measure.find_contours(img, d)
    #       for n,c in enumerate(npc):
    #         contours = [((x[1]-512)/1024*3499.99975586*2,(x[0]-512)/1024*3499.99975586*2) for x in c]
    #         if norm(c[-1] - c[0]) < 0.01:
    #           self.canvas.create_polygon(contours,fill="",outline='red',tag="contour")
Exemplo n.º 36
0
        clauses = len(rules)
        variables = len(truth_values)
        print('========= SAT Problem: {}/{} ========='.format(sdk, len(sudokus)))
        old_len = len(rules)
        print('   Initial number of rules:', len(rules), '\n')

        # We need it for data analysis
        init_len_clauses = len(rules)

        finish = False
        while finish == False:
            bk = False
            # Simplify
            rules, literals_dict, truth_values, split_choice, neg_literal, \
            rules_before_split, literals_dict_before_split, truth_values_before_split, results[4], bk = \
                simplify.simplify(rules, literals_dict, truth_values, split_choice, neg_literal,
                            rules_before_split, literals_dict_before_split, truth_values_before_split, results[4], bk)
            new_len = len(rules)
            print('    #clauses: after simplify:', new_len, end='\r')
            if new_len == 0 :
                # Solution
                if not check_sudoku.check_sudoku(sorted(list([val for val in truth_values if val > 0]))):
                    print(list(truth_values))
                    print(type(list(truth_values)[0]))

                    pretty_print.solution(truth_values)
                    quit()

                pretty_print.solution(truth_values)
                finish = True

                # get the solution time
Exemplo n.º 37
0
    # In case you're running this file from this folder.
    from data_processing import NewsQaDataset

if __name__ == "__main__":
    dir_name = os.path.dirname(os.path.abspath(__file__))

    parser = argparse.ArgumentParser()
    parser.add_argument('--cnn_stories_path',
                        default=os.path.join(dir_name, 'cnn_stories.tgz'),
                        help="The path to the CNN stories (cnn_stories.tgz).")
    parser.add_argument(
        '--dataset_path',
        default=os.path.join(dir_name, 'newsqa-data-v1.csv'),
        help="The path to the dataset with questions and answers.")
    args = parser.parse_args()

    newsqa_data = NewsQaDataset(args.cnn_stories_path, args.dataset_path)

    logger = logging.getLogger('newsqa')
    logger.setLevel(logging.INFO)

    # Dump the dataset to common formats.
    newsqa_data.dump(path='combined-newsqa-data-v1.json')
    newsqa_data.dump(path='combined-newsqa-data-v1.csv')

    tokenized_data_path = os.path.join(dir_name,
                                       'newsqa-data-tokenized-v1.csv')
    tokenize(output_path=tokenized_data_path)
    split_data(dataset_path=tokenized_data_path)
    simplify(output_dir_path='split_data')
Exemplo n.º 38
0
def test_solver_mult_basic():
    assert test_generator(simplify('5 * (4 * 3)')) == 60
    assert test_generator(simplify('5 * (4 * x)')) == M(20, 'x')
    assert test_generator(simplify('(x * 5) * 4 * 3')) == M(60, 'x')
    assert test_generator(simplify('(x * y * 5) * 4 * 3')) == M(60, 'x', 'y')
Exemplo n.º 39
0
def test_exponential_exponential_multiplication(capsys):
    abstract_syntax_tree = "3^3^2*2"
    expected = (3**9)*2
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 40
0
def test_minus_function(capsys):
    abstact_syntax_tree = ("FUNCTION", 'sin', ("NEGATIVE",  'pi'))
    expected = 0
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 41
0
def test_exponential_negative_exponential(capsys):
    abstract_syntax_tree = "9^-2"
    expected = 3
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 42
0
def test_functions_parenthesis(capsys):
    abstact_syntax_tree = ("FUNCTION", 'cos', ("TIMES", ("FUNCTION", 'cos', ("NEGATIVE", 'pi')), pi))
    expected = -1
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 43
0
def test_factorial_complex(capsys):
    abstract_syntax_tree = "-4!^3!"
    expected = -factorial(4) ** factorial(3)
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 44
0
 def simplify(self):
     import simplify
     return simplify.simplify(self)
Exemplo n.º 45
0
def test_empty(capsys):
    abstract_syntax_tree = ""
    expected = ""
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 46
0
def test_simplify_fractions():
    assert test_generator(simplify('a/b')) == F('a', 'b')
    assert test_generator(simplify('a/b/c/d/e')) == F('a', M('b', 'c', 'd', 'e'))
    assert test_generator(simplify('a/(b/(c/(d/e)))')) == F(M('a','c','e'),M('b','d'))
Exemplo n.º 47
0
def test_function(capsys):
    abstract_syntax_tree = "{sin$1}(0)"
    expected = ("FUNCTION", 'sin', 0)
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 48
0
hmax = e1 * (1 - imax) + e2 * imax
print(imin, imax)
print(e1, e2, e3, e4)
print(hmin, hmax)

contours = []
hstep = 10
nc = m.ceil((hmax - hmin) / hstep)
istep = (imax - imin) / nc
for i in range(nc):
    hgt = imin + i * istep
    h = hmin + i * hstep
    npc = measure.find_contours(img, hgt)
    cs = []
    for c in npc:
        c = simplify(c, 10, True)
        if len(c):
            print(h)
            cs.append(c)
            csa = np.array(cs)
            contours.append(csa)
np.savez_compressed(args.file + "-contours", *contours)

#     mi,ma = float(np.amin(img)),float(np.amax(img))
#     print("contour",mi,ma)
#     for i in range(50):
#       d = float(mi*(1-i/50)+ma*i/50)
#       print("contour",d)
#       npc = measure.find_contours(img, d)
#       for n,c in enumerate(npc):
#         contours = [((x[1]-512)/1024*3499.99975586*2,(x[0]-512)/1024*3499.99975586*2) for x in c]
Exemplo n.º 49
0
def test_function_1_function_1(capsys):
    abstact_syntax_tree = ("FUNCTION", 'cos', ("FUNCTION", 'sin', 0))
    expected = 1
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 50
0
def test_solver_plus():
    assert test_generator(simplify('5 + 4 + 3')) == 12
    assert test_generator(simplify('5 + x + x + 3')) == P(8, M(2, 'x'))
Exemplo n.º 51
0
def test_define_function_0(capsys):
    abstact_syntax_tree = ("ASSIGN", 'hello', 5)
    expected = 5
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 52
0
def test_number(capsys):
    abstract_syntax_tree = 7
    expected = 7
    assert expected == simplify(abstract_syntax_tree)
Exemplo n.º 53
0
def test_multiplication(capsys):
    abstract_syntax_tree = ("TIMES", 4, 3, 10)
    expected = 120
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 54
0
def test_parenthesis_division(capsys):
    abstract_syntax_tree = "1000/(90 + 10)"
    expected = 10
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 55
0
def test_division_multiplication(capsys):
    abstract_syntax_tree = ("TIMES", ("DIVIDE", 50, 10), 5)
    expected = 25
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 56
0
def test_exponential(capsys):
    abstract_syntax_tree = "2^5"
    expected = 2**5
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 57
0
def test_parenthesis_whole(capsys):
    abstract_syntax_tree = ("MINUS", 11 1)
    expected = 10
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 58
0
print_heuristic = ['Basic DPLL (random)', 'Jeroslow-Wang method
', 'MOMs method']
print('    Heuristic: ', print_heuristic[which_method])
print('=====================================\n')

old_clauses_count = len(rules)
back_track_count = 0
split_count = 0
done = False
problem_start_time = time.time()

while done == False:
    back_track = False
    # Simplify
    rules, literals_dict, truth_values, split_choice, neg_literal, \
    rules_before_split, literals_dict_before_split, truth_values_before_split, back_track = \
        simplify.simplify(rules, literals_dict, truth_values, split_choice, neg_literal,
                          rules_before_split, literals_dict_before_split, truth_values_before_split,back_track)
    new_clauses_count = len(rules)

    if back_track:
        back_track_count += 1

    if new_clauses_count == 0:
        print('The problem has a solution -- SAT')
        print("Solved in {0:.2f}s".format(time.time() - problem_start_time))
        print("Number of splits: {}".format(split_count))
        print("Number of backtracks: {}".format(back_track_count))
        print('The solution can be found at the file: {}.out'.format(str(file)))
        print('')
        done = True

    elif old_clauses_count == new_clauses_count and back_track == False:
Exemplo n.º 59
0
def test_parenthesis_unary(capsys):
    abstract_syntax_tree = "-(-1)"
    expected = 1
    assert simplify(abstract_syntax_tree) = expected
Exemplo n.º 60
0
def test_solver_mult_fractions():
    assert test_generator(simplify('5 * (4 / y)')) == F(20, 'y')
    assert test_generator(simplify('4 / x * y * 1 * z')) == F(M(4.0, 'y', 'z'), 'x')
    assert test_generator(simplify('4 / x * (y / 1) * z')) == F(M(4, 'y', 'z'), 'x')
    assert test_generator(simplify('4 / x * (y * 1) * z')) == F(M(4, 'y', 'z'), 'x')
    assert test_generator(simplify('3 * x / 4 * y')) == F(M(3, 'x', 'y'), 4)