Exemple #1
0
def test_solve():
    from util import solve

    assert 26 == solve("2 * 3 + (4 * 5)")
    assert 437 == solve("5 + (8 * 3 + 9 + 3 * 4 * 3)")
    assert 12240 == solve("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))")
    assert 13632 == solve("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2")
def test_solve_env():
  with temp_ampl_file() as ampl_file:
    with util.solve(ampl_file.name, solver=mock_solver,
                    solver_options={'print_env': 1}) as result:
      assert result.output == str(os.environ) + '\n'
    env = {'foo': 'bar'}
    with util.solve(ampl_file.name, solver=mock_solver,
                    solver_options={'print_env': 1}, env=env) as result:
      assert result.output == str(env) + '\n'
def test_solve_env():
    with temp_ampl_file() as ampl_file:
        with util.solve(ampl_file.name,
                        solver=mock_solver,
                        solver_options={'print_env': 1}) as result:
            assert result.output == str(os.environ) + '\n'
        env = {'foo': 'bar'}
        with util.solve(ampl_file.name,
                        solver=mock_solver,
                        solver_options={'print_env': 1},
                        env=env) as result:
            assert result.output == str(env) + '\n'
def test_solve_timeout():
    start_time = time.time()
    with util.solve(os.path.join(repo_dir, 'nlmodels', 'camel1u.mod'),
                    solver=solver,
                    timeout=1) as result:
        elapsed_time = time.time() - start_time
        assert elapsed_time >= 1 and elapsed_time < 2
def test_solver_options():
    with temp_ampl_file() as ampl_file:
        with util.solve(ampl_file.name,
                        solver=mock_solver,
                        solver_options={
                            'foo': 42,
                            'bar': 'baz'
                        }) as result:
            assert result.output.endswith("'-AMPL', 'foo=42', 'bar=baz']\n")
Exemple #6
0
 def test_solve(self):
   self.assertEqual(0, util.solve(10, (0, 3, 6)))
   self.assertEqual(1, util.solve(2020, (1, 3, 2)))
   self.assertEqual(10, util.solve(2020, (2, 1, 3)))
   self.assertEqual(27, util.solve(2020, (1, 2, 3)))
   self.assertEqual(78, util.solve(2020, (2, 3, 1)))
   self.assertEqual(438, util.solve(2020, (3, 2, 1)))
   self.assertEqual(1836, util.solve(2020, (3, 1, 2)))
def test_solve():
  with temp_ampl_file() as ampl_file:
    nl_filename = None
    sol_filename = None
    with util.solve(ampl_file.name, solver=mock_solver) as result:
      sol_filename = result.sol_filename
      nl_filename = os.path.splitext(sol_filename)[0] + '.nl'
      assert(os.path.exists(nl_filename))
      assert(os.path.exists(sol_filename))
    assert(not os.path.exists(nl_filename))
    assert(not os.path.exists(sol_filename))
def test_solve():
    with temp_ampl_file() as ampl_file:
        nl_filename = None
        sol_filename = None
        with util.solve(ampl_file.name, solver=mock_solver) as result:
            sol_filename = result.sol_filename
            nl_filename = os.path.splitext(sol_filename)[0] + '.nl'
            assert (os.path.exists(nl_filename))
            assert (os.path.exists(sol_filename))
        assert (not os.path.exists(nl_filename))
        assert (not os.path.exists(sol_filename))
def test_solve_on_nl_file():
  nl_filename = []
  solver_options = {'foo': 0}
  def on_nl_file(nl_file, args):
    nl_filename.append(nl_file.name)
    assert os.path.exists(nl_file.name)
    solver_options['foo'] = 42
  with temp_ampl_file() as ampl_file:
    with util.solve(ampl_file.name, solver=mock_solver,
                    solver_options=solver_options, on_nl_file=on_nl_file) as result:
      sol_filename = result.sol_filename
      assert nl_filename[0] == os.path.splitext(sol_filename)[0] + '.nl'
      assert 'foo=42' in result.output
Exemple #10
0
  def test_solve_part2(self):
    inputs = (
      (175594, (0, 3, 6)),
      (2578, (1, 3, 2)),
      (3544142, (2, 1, 3)),
      (261214, (1, 2, 3)),
      (6895259, (2, 3, 1)),
      (18, (3, 2, 1)),
      (362, (3, 1, 2)))

    print('')
    for i in inputs:
      self.assertEqual(i[0], util.solve(30000000, i[1]))
      print('Passed for %s' % str(i[1]))
Exemple #11
0
def test_solve_interrupt():
  with temp_ampl_file() as ampl_file:
    # Check if files are deleted even in case of KeyboardInterrupt.
    caught = False
    try:
      with util.solve(ampl_file.name, solver=mock_solver) as result:
        sol_filename = result.sol_filename
        nl_filename = os.path.splitext(sol_filename)[0] + '.nl'
        assert(os.path.exists(nl_filename))
        assert(os.path.exists(sol_filename))
        raise KeyboardInterrupt()
    except KeyboardInterrupt:
      caught = True
    assert(caught)
    assert(not os.path.exists(nl_filename))
    assert(not os.path.exists(sol_filename))
def test_solve_interrupt():
    with temp_ampl_file() as ampl_file:
        # Check if files are deleted even in case of KeyboardInterrupt.
        caught = False
        try:
            with util.solve(ampl_file.name, solver=mock_solver) as result:
                sol_filename = result.sol_filename
                nl_filename = os.path.splitext(sol_filename)[0] + '.nl'
                assert (os.path.exists(nl_filename))
                assert (os.path.exists(sol_filename))
                raise KeyboardInterrupt()
        except KeyboardInterrupt:
            caught = True
        assert (caught)
        assert (not os.path.exists(nl_filename))
        assert (not os.path.exists(sol_filename))
def test_solve_on_nl_file():
    nl_filename = []
    solver_options = {'foo': 0}

    def on_nl_file(nl_file, args):
        nl_filename.append(nl_file.name)
        assert os.path.exists(nl_file.name)
        solver_options['foo'] = 42

    with temp_ampl_file() as ampl_file:
        with util.solve(ampl_file.name,
                        solver=mock_solver,
                        solver_options=solver_options,
                        on_nl_file=on_nl_file) as result:
            sol_filename = result.sol_filename
            assert nl_filename[0] == os.path.splitext(sol_filename)[0] + '.nl'
            assert 'foo=42' in result.output
Exemple #14
0
def main():
    if DOWNLOAD_DATA:
        try:
            download_sudokus()
            load_qqwing_sudokus()
        except:
            print("Some downloads went wrong...")

        plagiarism = antiplagiarism("./sudokus",
                                    type=".txt",
                                    grams=2,
                                    threshold=0.9)
        print("number of sudokus that are very similar:", len(plagiarism),
              "(over 90% of similarity)")

    if LOAD_KAGGLE:
        cc.reset()
        init = time.time()
        count = 0
        solved = 0
        nrows = 0 + 100000
        skip = 0
        c = Redis(host='192.168.1.237')
        q = Queue(connection=c)
        jobs = []
        dataset = list(os.listdir("./sudoku_csvs/")).filter(
            lambda x: "sudoku.csv" in x
        )  #.filter(lambda x: "reduced_sudokus_kaggle.csv" in x)

        for i in dataset:
            print("loading sudokus from kaggle's csv:", i)
            ds = pd.read_csv("./sudoku_csvs/" + i, nrows=nrows)
            nrows = nrows - skip
            for en, j in enumerate(ds.iterrows()):
                if en < skip:
                    continue
                curr_sudoku = parse_sudoku(j[1]["quizzes"])
                sol_sudoku = parse_sudoku_sol(j[1]["solutions"])

                if DISTRIBUTE:
                    jobs.append(
                        q.enqueue(solve, Sudodata(curr_sudoku, sol_sudoku)))
                    count += 1
                    print("\r [DISTRIBUTED] Distributed sudokus: ",
                          count,
                          "out of",
                          nrows,
                          end='')
                else:
                    result = solve(Sudodata(curr_sudoku, sol_sudoku))

                    if result != -1:
                        if VIEW_RESULTS:
                            print("--------------------------")
                            print(result)
                        solved += 1
                    count += 1
                    print("\r [SEQUENTIAL] Solved sudokus:",
                          count,
                          "out of",
                          nrows,
                          "[Elapsed:", (time.time() - init) / 60,
                          "mins]",
                          "[Projection:",
                          nrows / count * ((time.time() - init) / 60),
                          "mins]",
                          "[Avg:", (time.time() - init) / count,
                          "secs]",
                          end='')

        if DISTRIBUTE:
            solved = print_distributed_results(jobs, nrows, init)

        print()
        print("Tot of correct over all:", solved, "/", nrows)
        print("Accuracy is: %.2f" % ((solved / nrows) * 100), "%")
        print("Elapsed:", (time.time() - init) / 60, "min")
        print("recursion count", cc.get_num_recursive_calls(),
              ", mean of recursions per sudoku:",
              cc.get_num_recursive_calls() / nrows, "recs/sudoku")
        print("constraint prop count", cc.get_num_constraints_prop_calls(),
              ", mean of constr. prop. per sudoku:",
              cc.get_num_constraints_prop_calls() / nrows,
              "const.props/sudoku")
        print("Coefficient of mean difficulty is:",
              cc.get_num_occupied_cells() / nrows,
              "(higher means easier sudokus)")
        print("----------------------------------------------------------")

    if WEBSCRAPED:
        cc.reset()
        init = time.time()
        count = 0
        solved = 0
        dataset = list(os.listdir("./sudokus")).filter(
            lambda x: ".txt" in x)[:10]  # or ("norvig" in x))
        num_sudoku_avail = len(dataset)
        c = Redis(host='192.168.1.237')
        q = Queue(connection=c)
        jobs = []
        for i in dataset:
            # i is a txt file representing a sudoku in the correct format
            #try:
            with open("./sudokus/" + i, mode="r") as f:
                curr_sudoku = parse_sudoku(f)

                if DISTRIBUTE:
                    jobs.append(q.enqueue(solve, Sudodata(curr_sudoku)))
                    count += 1
                    print("\r [DISTRIBUTED] Distributed sudokus: ",
                          count,
                          "out of",
                          num_sudoku_avail,
                          end='')
                else:
                    result = solve(Sudodata(curr_sudoku))

                    if result != -1:
                        if VIEW_RESULTS:
                            print("--------------------------")
                            print(result)
                        solved += 1
                    count += 1
                    print("\r [SEQUENTIAL] Solved sudokus:",
                          count,
                          "out of",
                          num_sudoku_avail,
                          "[Elapsed:", (time.time() - init) / 60,
                          "mins]",
                          "[Projection:",
                          num_sudoku_avail / count *
                          ((time.time() - init) / 60),
                          "mins]",
                          "[Avg:", (time.time() - init) / count,
                          "secs]",
                          end='')
        # except:
        # 	print("A sudoku was wrongly formatted, in particular:", i)

        if DISTRIBUTE:
            solved = print_distributed_results(jobs, num_sudoku_avail, init)

        print()
        print("Tot of correct over all:", solved, "/", num_sudoku_avail)
        print("Accuracy is: %.2f" % ((solved / num_sudoku_avail) * 100), "%")
        print("Elapsed:", (time.time() - init) / 60, "min")
        print("recursion count", cc.get_num_recursive_calls(),
              ", mean of recursions per sudoku:",
              cc.get_num_recursive_calls() / num_sudoku_avail, "recs/sudoku")
        print("constraint prop count", cc.get_num_constraints_prop_calls(),
              ", mean of constr. prop. per sudoku:",
              cc.get_num_constraints_prop_calls() / num_sudoku_avail,
              "const.props/sudoku")
        print("Coefficient of mean difficulty is:",
              cc.get_num_occupied_cells() / num_sudoku_avail,
              "(higher means easier sudokus)")
        print("----------------------------------------------------------")
Exemple #15
0
def solve(input_path):
    f = open(input_path)
    nums = [int(s) for s in f.readline().split(',')]
    return util.solve(30000000, nums)
Exemple #16
0
def test_solve_timeout():
  start_time = time.time()
  with util.solve(os.path.join(repo_dir, 'nlmodels', 'camel1u.mod'),
                  solver=solver, timeout=1) as result:
    elapsed_time = time.time() - start_time
    assert elapsed_time >= 1 and elapsed_time < 2
Exemple #17
0
def test_solver_options():
  with temp_ampl_file() as ampl_file:
    with util.solve(ampl_file.name, solver=mock_solver,
                    solver_options={'foo': 42, 'bar': 'baz'}) as result:
      assert result.output.endswith("'-AMPL', 'foo=42', 'bar=baz']\n")