当前位置: 首页>>代码示例>>Python>>正文


Python Solver.solve方法代码示例

本文整理汇总了Python中solver.Solver.solve方法的典型用法代码示例。如果您正苦于以下问题:Python Solver.solve方法的具体用法?Python Solver.solve怎么用?Python Solver.solve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在solver.Solver的用法示例。


在下文中一共展示了Solver.solve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: play

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
 def play(self, login, password):
     game_controller = GameController()
     game_controller.load_board()
     board = self.get_board()
     # self.board.show()
     solver = Solver(board)
     solver.solve()
开发者ID:wkamel,项目名称:slowotok,代码行数:9,代码来源:main.py

示例2: test_linear_comparisions

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
def test_linear_comparisions():
    solver = Solver()
    x = variable('x')
    y = variable('y')
    t = solver.solve((x + 9 * y) == 10)
    assert t['y'] == t['x'] is True

    s = solver.solve((x + 9 * y) != 10)
    assert not (s['x'] and s['y'])
开发者ID:DRMacIver,项目名称:PseudoBoolean,代码行数:11,代码来源:test_solver.py

示例3: main

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
def main():
    args = parse_args()
    f = open(args.puzzle)

    g = Grid()
    s = Solver(g)
    s.populate(puzzle_start_input(f.readlines()))
    print g
    s.solve()
    print g
开发者ID:dgkimura,项目名称:sudoku,代码行数:12,代码来源:sudoku.py

示例4: worker_solve

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
def worker_solve(solveable, mutateable, log):
    s = Solver()
    while True:
        try:
            f = solveable.get(block=False)
            s.solve(f)
            log.put("Solver: solved   %s" % f.__unicode__())
            mutateable.put(f)
        except Empty:
            time.sleep(0.1)
开发者ID:bennullgraham,项目名称:Angion,代码行数:12,代码来源:pool.py

示例5: finetune

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
 def finetune(self, X, batch_size, n_iter, optimizer, l_rate, decay, lr_scheduler=None):
     def l2_norm(label, pred):
         return np.mean(np.square(label-pred))/2.0
     solver = Solver('sgd', momentum=0.9, wd=decay, learning_rate=l_rate, lr_scheduler=lr_scheduler)
     solver.set_metric(mx.metric.CustomMetric(l2_norm))
     solver.set_monitor(Monitor(1000))
     data_iter = mx.io.NDArrayIter({'data': X}, batch_size=batch_size, shuffle=False,
                                   last_batch_handle='roll_over')
     logging.info('Fine tuning...')
     solver.solve(self.xpu, self.loss, self.args, self.args_grad, data_iter,
                  0, n_iter, {}, False)
开发者ID:Aspart,项目名称:mxnet,代码行数:13,代码来源:autoencoder.py

示例6: cluster

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
    def cluster(self, X, y=None, update_interval=None):
        N = X.shape[0]
        if not update_interval:
            update_interval = N
        batch_size = 256
        test_iter = mx.io.NDArrayIter({"data": X}, batch_size=batch_size, shuffle=False, last_batch_handle="pad")
        args = {k: mx.nd.array(v.asnumpy(), ctx=self.xpu) for k, v in self.args.items()}
        z = model.extract_feature(self.feature, args, None, test_iter, N, self.xpu).values()[0]
        kmeans = KMeans(self.num_centers, n_init=20)
        kmeans.fit(z)
        args["dec_mu"][:] = kmeans.cluster_centers_
        solver = Solver("sgd", momentum=0.9, wd=0.0, learning_rate=0.01)

        def ce(label, pred):
            return np.sum(label * np.log(label / (pred + 0.000001))) / label.shape[0]

        solver.set_metric(mx.metric.CustomMetric(ce))

        label_buff = np.zeros((X.shape[0], self.num_centers))
        train_iter = mx.io.NDArrayIter(
            {"data": X}, {"label": label_buff}, batch_size=batch_size, shuffle=False, last_batch_handle="roll_over"
        )
        self.y_pred = np.zeros((X.shape[0]))

        def refresh(i):
            if i % update_interval == 0:
                z = model.extract_feature(self.feature, args, None, test_iter, N, self.xpu).values()[0]
                p = np.zeros((z.shape[0], self.num_centers))
                self.dec_op.forward([z, args["dec_mu"].asnumpy()], [p])
                y_pred = p.argmax(axis=1)
                print np.std(np.bincount(y_pred)), np.bincount(y_pred)
                print np.std(np.bincount(y.astype(np.int))), np.bincount(y.astype(np.int))
                if y is not None:
                    print (cluster_acc(y_pred, y)[0])
                weight = 1.0 / p.sum(axis=0)
                weight *= self.num_centers / weight.sum()
                p = (p ** 2) * weight
                train_iter.data_list[1][:] = (p.T / p.sum(axis=1)).T
                print np.sum(y_pred != self.y_pred), 0.001 * y_pred.shape[0]
                if np.sum(y_pred != self.y_pred) < 0.001 * y_pred.shape[0]:
                    self.y_pred = y_pred
                    return True
                self.y_pred = y_pred

        solver.set_iter_start_callback(refresh)
        solver.set_monitor(Monitor(50))

        solver.solve(self.xpu, self.loss, args, self.args_grad, None, train_iter, 0, 1000000000, {}, False)
        self.end_args = args
        if y is not None:
            return cluster_acc(self.y_pred, y)[0]
        else:
            return -1
开发者ID:253681319,项目名称:mxnet,代码行数:55,代码来源:dec.py

示例7: Detector

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
class Detector(tornado.websocket.WebSocketHandler):
      def __init__(self, *args, **kwargs):
            self.solver = Solver()
            super(Detector, self).__init__(*args, **kwargs)
        
      def open(self):
            print 'new connection'

      def on_message(self, message):
            image = Image.open(StringIO.StringIO(message))
            cv_image = numpy.array(image)
            if(cv_image.shape):
                self.process(cv_image)

      def on_close(self):
            print 'connection closed'

      def process(self, cv_image):
            loc = self.solver.solve(cv_image)
            print loc
            if (loc):
              result = json.dumps(loc)
            else:
              result = json.dumps((-1,-1,-1,-1))
            self.write_message(result)
开发者ID:tianyaqu,项目名称:mustache,代码行数:27,代码来源:wshandler.py

示例8: test_solve_ordering_between_variables

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
def test_solve_ordering_between_variables():
    solver = Solver()
    x = variable('x')
    y = variable('y')
    t = solver.solve(x < y)
    assert t['x'] is False
    assert t['y'] is True
开发者ID:DRMacIver,项目名称:PseudoBoolean,代码行数:9,代码来源:test_solver.py

示例9: test_2x1_trivial

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
 def test_2x1_trivial(self):
     solver = Solver(""" 2x1:.12
                         1 .
                         ---
                         . . """)
     solutions = solver.solve()[0]
     self.assertEqual(1, len(solutions))
开发者ID:szabopeter,项目名称:sudokusolver,代码行数:9,代码来源:test_basics.py

示例10: compare_text

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
    def compare_text(self, files):
        """
        Compares the original plain text with the decrypted one
        """

        plain_txt = CipherText(files['plain'])
        cipher_txt = CipherText(files['encoded'])
        corpus = CorpusStats(self.corpus_file)
        solver = Solver(cipher_txt, corpus)

        best_solution = solver.solve(corpus)

        def clean(w_list):
            """
            Cleans up white spaces
            """
            return [w.strip(' \r\t') for w in w_list if w.strip(' \r\t')]

        w_enc = clean(cipher_txt.words)
        w_dec = clean(plain_txt.words)


        n_solved = 0.0
        for encoded, actual in zip(w_enc, w_dec):
            decoded = textutil.decode_word(encoded, best_solution)
            if decoded == actual:
                n_solved += 1.0
            else:
                print "Mismatch! Expected: ", actual, "but got: ", decoded

        return n_solved, len(cipher_txt.words)
开发者ID:eigenfun,项目名称:cipher-decryption,代码行数:33,代码来源:testdecode.py

示例11: test_3x3_trivial

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
 def test_3x3_trivial(self):
     solver = Solver("""
                     ..6|..9|47.
                     .8.|.6.|..5
                     .47|..5|..1
                     -----------
                     2..|...|.59
                     ...|9.3|...
                     .7.|...|..3
                     -----------
                     8..|3..|12.
                     7..|.2.|.9.
                     .21|6..|3..
                     """)
     solutions = solver.solve()[0]
     self.assertEqual(1, len(solutions))
     solution = solutions[0]
     expected_lines = [
         "3x3:.123456789",
         "356819472",
         "182764935",
         "947235861",
         "238146759",
         "615973284",
         "479582613",
         "894357126",
         "763421598",
         "521698347"
         ]
     expected_solution = "\n".join(expected_lines)
     self.assertEqual(expected_solution, solution.asText())
开发者ID:szabopeter,项目名称:sudokusolver,代码行数:33,代码来源:test_basics.py

示例12: test_2x1_backtracking

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
 def test_2x1_backtracking(self):
     solver = Solver(""" 2x1:.12
                         . .
                         ---
                         . . """)
     solutions = solver.solve()[0]
     self.assertEqual(2, len(solutions))
开发者ID:szabopeter,项目名称:sudokusolver,代码行数:9,代码来源:test_basics.py

示例13: main

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
def main():
    """
    Entry point into the decryption process
    """

    # If the corpus and encoded file paths are not provided in the
    # command line arguments, pick the default files
    if len(sys.argv) < 3:
        print """
        Assuming default paths for the corpus and encrypted files:
        ./corpus-en.txt' and ./encoded-en.txt.

        If they are located somewhere else, please run the script
        with command-line arguments specifying the file locations.
        For example:

        python ./decode.py ./data/corpus-en.txt ./data/encoded-en.txt
        """

        corpus_file = 'corpus-en.txt'
        encrypted_file = 'encoded-en.txt'
    else:
        corpus_file, encrypted_file = sys.argv[1], sys.argv[2]

    # Read the encoded file and the corpus
    cipher_txt = CipherText(encrypted_file)
    corpus = CorpusStats(corpus_file)
    solver = Solver(cipher_txt, corpus)
    # Compute the solution
    best_solution = solver.solve(corpus)

    print """
    Writing the decrypted text to file:
    ./decoded.txt

    the best solution key to file:
    ./decryption_cipher.txt

    original encryption key to file:
    ./encryption_cipher.txt
    """

    # Write the solutions
    file_decrypt_cipher = open("decryption_cipher.txt", 'w')
    file_encrypt_cipher = open("encryption_cipher.txt", 'w')
    for char in textutil.A2Z:
        if char in best_solution:
            file_decrypt_cipher.write(
                char + ' -> ' + best_solution[char] + '\n')
            file_encrypt_cipher.write(
                best_solution[char] + ' -> ' + char + '\n')
        else:
            file_decrypt_cipher.write(char + ' -> ?' + '\n')
            file_encrypt_cipher.write('? -> ' + char + '\n')

    file_decrypt_cipher.close()
    file_encrypt_cipher.close()
    cipher_txt.decode(best_solution, 'decoded.txt')
开发者ID:eigenfun,项目名称:cipher-decryption,代码行数:60,代码来源:decode.py

示例14: main

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
def main():
	"""Solves the Navier-Stokes equations in a two-dimensional domain
	with an immersed boundary method."""

	# parse the command-line
	args = read_inputs()

	# create the case
	Case(args.path)

	# create the computational domain
	Domain(is_show=args.mesh)
	
	# create the solver
	solver = Solver()

	# solve the Navier-Stokes equations
	solver.solve(body=Domain.body)
开发者ID:GitDerek,项目名称:pyIBM,代码行数:20,代码来源:pyIBM.py

示例15: main

# 需要导入模块: from solver import Solver [as 别名]
# 或者: from solver.Solver import solve [as 别名]
def main():
    input_file = sys.argv[1] if len(sys.argv) == 2 else 'input.txt'
    s = Solver(input_file)
    winning_state = s.solve()
    solution = [ winning_state ]
    while solution[0].prev_state is not None:
        solution.insert(0, solution[0].prev_state)
    p = Printer()
    p.print_solution(solution, 4)
开发者ID:alegen,项目名称:rush-hour,代码行数:11,代码来源:main.py


注:本文中的solver.Solver.solve方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。