Beispiel #1
0
    def test_reMach(self):
        msg = """
===        
RegExp:%s        
Text:%s
NOT MACH ===
                """
        lanRules = Rules()
        Format = lanRules.get('Format', 'pattern')
#         print(lanRules.get('Filter', 'pattern'))
        Filter = lanRules['Filter']['pattern']
        Blank = lanRules['Blank']['pattern']
        print(Blank)
        testSamples = [
                        # [resault,regExp,Text,re.report]
                        [True, r'hello', 'hello world!'],
                        [True, Format, 'E\tE/_1_=English\tS/_1_=简体中文'],
                        [False, Format, 'E\tE/_2_=English\tS/_1_=简体中文'],
                        [True, Format, 'F\tF/_16_=la touche # pour entrer espace\tS/_16_=#键输入空格\t35'],

                        [True, Filter, 'E\t#E/_1_=English\tS/_1_=简体中文'],
                        [True, Filter, 'E\tE/_1_=English\t#S/_1_=简体中文'],
                        [True, Filter, 'E\tE/_1_=English\tS/1_=简体中文'],  # 基准字段格式检测错误,也会排除
                        [True, Filter, 'G\tF/_16_=la touche # pour entrer espace\tS/_1k6_=#键输入空格    35'],
                        [True, Blank, 'E/_1_=Eng   lish'],
                     ]

        for mustRet, regExp, text in testSamples:
            resault = Rules().Test(regExp, text)
            emsg = msg % (regExp, text)
            self.assertEqual(resault, mustRet, emsg)
        pass
    def __init__(self, objective, parent=None):
        super(QuestionWidget, self).__init__(parent)
        self.objective = objective
        self.memRules = Rules("rulelist.json")
        self.reasoned = []

        # Get consequents, antecedents and list of rules pertaining the objective
        related = self.memRules.GetRelatedRules(self.objective)
        self.cons = related["CONS"]
        self.ants = related["ANTS"]

        # Generate question list
        self.question_list = []
        for con in self.cons[1:]:
            self.question_list.append(con)
        for ant in self.ants:
            self.question_list.append(ant)
        self.question = ""

        self.ruleHeap = Rules()
        for rule in related["RULES"]:
            self.ruleHeap.CreateRule(rule)

        # Value log will be a workmemory object
        self.valueLog = WorkMemory()

        self.lbl = QLabel('Especifique el valor de "<ID>":')

        self.value_edit = QComboBox()
        self.value_edit.addItem("T")
        self.value_edit.addItem("F")

        self.replace_btn = QPushButton("Replace")
        self.replace_btn.clicked.connect(self.Replace)

        self.rules_heap = QPlainTextEdit()
        self.rules_heap.setReadOnly(True)
        self.value_logs = QPlainTextEdit()
        self.value_logs.setReadOnly(True)

        self.hlayout1 = QHBoxLayout()
        self.hlayout1.addWidget(self.lbl)
        self.hlayout1.addWidget(self.value_edit)
        self.hlayout1.addWidget(self.replace_btn)

        self.hlayout2 = QHBoxLayout()
        self.hlayout2.addWidget(self.rules_heap)
        self.hlayout2.addWidget(self.value_logs)

        self.main_layout = QVBoxLayout()
        self.main_layout.addLayout(self.hlayout1)
        self.main_layout.addLayout(self.hlayout2)

        self.UpdateValueLog()
        self.UpdateRuleHeap()
        self.SetNextQuestion()

        self.setLayout(self.main_layout)
        self.setWindowTitle("Objective Reasoning - Questioning")
        self.show()
Beispiel #3
0
    def make_move(self, move: str, white):
        match = self.pattern.match(move)

        piece_type = Pieces.get(
            'p' if match.group(1) == '' else match.group(1), white=True)
        move = match.group(2).replace('x', '')
        promotion = match.group(3)

        rules = Rules()
        rules.put(self._board,
                  self.en_passant,
                  self.wk,
                  self.wq,
                  self.bk,
                  self.bq,
                  promote=None if promotion == '' else promotion)

        exact_row, exact_col = '', ''
        if move.lower() == 'o-o':
            if white:
                move = 'g1'
            else:
                move = 'g8'
            piece_type = 'K'
        elif move.lower() == 'o-o-o':
            if white:
                move = 'c1'
            else:
                move = 'c8'
            piece_type = 'K'
        elif len(move) == 3:
            char = move[0]
            move = move[-2:]
            if char.isdigit():
                exact_col = char
            else:
                exact_row = char

        pieces, possible_moves = rules.pieces, rules.possible_moves
        for piece, moves in zip(pieces, possible_moves):
            if piece_type == Pieces.get(piece.type, True) and piece.is_white == white and move in moves \
                    and exact_row in piece.square and exact_col in piece.square:

                board_copy = self._board.copy()
                board_copy.update_squares(*rules.make_move(piece.square, move))
                rules_check = Rules()
                rules_check.put(board_copy, self.en_passant, self.wk, self.wq,
                                self.bk, self.bq)
                status = rules_check.status(white)

                if status == Rules.NORMAL:
                    previous_board = self._board.copy()
                    self._board.update_squares(
                        *rules.make_move(piece.square, move))
                    self.update_castle(*Rules.castle_rights(self._board))
                    self.en_passant = Rules.find_en_passant(
                        self._board, previous_board)
                    break
Beispiel #4
0
def sort_hand(cards, game_type):
    if not game_type:
        return sorted(cards, key=lambda card: Rules().cards.index(card))

    sorted_trumps = Rules().get_sorted_trumps(game_type=game_type)
    trumps = sorted([card for card in cards if card in sorted_trumps], key= lambda card : sorted_trumps.index(card))
    non_trumps = sorted([card for card in cards if card not in sorted_trumps], key=lambda card: Rules().cards.index(card))

    return non_trumps + trumps
Beispiel #5
0
    def __init__(self,
                 base_directory=None,
                 verbose=False,
                 being_tested=False,
                 ignore_temp_rules=False,
                 ignore_specific_rules=False):
        """Creates a new DepsBuilder.

    Args:
      base_directory: local path to root of checkout, e.g. C:\chr\src.
      verbose: Set to True for debug output.
      being_tested: Set to True to ignore the DEPS file at tools/checkdeps/DEPS.
      ignore_temp_rules: Ignore rules that start with Rule.TEMP_ALLOW ("!").
    """
        base_directory = (base_directory or os.path.join(
            os.path.dirname(__file__), os.path.pardir, os.path.pardir))
        self.base_directory = os.path.abspath(
            base_directory)  # Local absolute path
        self.verbose = verbose
        self._under_test = being_tested
        self._ignore_temp_rules = ignore_temp_rules
        self._ignore_specific_rules = ignore_specific_rules

        # Set of normalized paths
        self.git_source_directories = _GitSourceDirectories(
            self.base_directory)

        # Map of normalized directory paths to rules to use for those
        # directories, or None for directories that should be skipped.
        # Normalized is: absolute, lowercase, / for separator.
        self.directory_rules = {}
        self._ApplyDirectoryRulesAndSkipSubdirs(Rules(), self.base_directory)
Beispiel #6
0
def main():
    rules = Rules()
    rulefunc = getattr(rules, rule)
    lastfld = None
    # t = Thing(fld, cell, Location(0,0))
    # t.program = list("ddrrrull")
    # things.generate()
    rooms = add_rooms()
    # for r in rooms:
    # for l in r.tpoints: fld.put('*', Location(l))
    # print [str(r) for r in rooms]
    corridors = Corridors(fld, rooms)
    corridors.create()
    fld.display()
    return

    for i in range(period):
        rules.n = i
        for thing in things:
            thing.movep()
        # if p: t.movep()
        for location in fld:
            val = fld.value(location)
            rulefunc(fld, location, val, len(fld.live_neighbours(location)))

        fld.display()
        print ' ' + "%d/%d add:%d" % (i + 1, period, rules.add)
        sleep(interval)
        lastfld = fld.field
Beispiel #7
0
    def __init__(self, allmessages, debug=False):
        #generate all ``Rule``s that the ``Message``s will be checked against
        rules = Rules().rules
        self.document_plans = []
        for index, book in enumerate(allmessages.books):
            before = time()

            messages = book.messages.values(
            )  #all messages about a single book
            plan = generate_textplan(messages, rules, book.book_score)

            after = time()
            time_diff = after - before
            self.document_plans.append(plan)

            if debug == True:
                print "Plan {0}: generated in {1} seconds.\n".format(
                    index, time_diff, plan)
                book_title = book.messages['id']['title']

                if index > 0:
                    lastbook = allmessages.books[index - 1]
                    lastbook_title = lastbook.messages['id']['title']
                    print "Comparing '{0}' " \
                          "with '{1}':\n\n{2}".format(book_title,
                                                      lastbook_title, plan)
                else:
                    print "Describing '{0}':\n\n{1}".format(book_title, plan)
Beispiel #8
0
    def __init__(self):
        self.games_board = Board(8)
        self.game_view = View(self.games_board)
        self.rules_game = Rules(self.games_board)

        self.player_one = HumanPlayer(Disk.DARK)
        self.player_two = RandomPlayer(Disk.LIGHT)
Beispiel #9
0
 def setSeed(self, seed):
     if seed == None:
         seed = int(time.time() * 1000) % 2**32
     np.random.seed(seed)
     random.seed(seed)
     torch.manual_seed(seed)
     self.rules = Rules()
Beispiel #10
0
    def __init__(self, dealer):

        self.rules = Rules()

        self.dealer = dealer
        self.game_type = [None, None]
        self.game_player = None
        self.first_player = (dealer + 1) % 4
        self.trick_number = 0
        self.played_cards = 0

        self.game_stage = None

        # who wants to play what
        self.bidding_round = [[None, None] for x in range(4)]

        # who doubled the game (kontra / retour)
        self.contra_retour = []

        # cards ordered by players
        self.course_of_game_playerwise = [[[None, None] for x in range(4)]
                                          for y in range(8)]

        # cards ordered by the time they were played
        self.course_of_game = [[[None, None] for x in range(4)]
                               for y in range(8)]

        # which player took the trick
        self.trick_owner = [None] * 8

        self.scores = [0, 0, 0, 0]

        #for debugging purposes remember probs for picking an action
        self.action_probabilities = [[[None, None] for x in range(4)]
                                     for y in range(11)]
Beispiel #11
0
 def test_four_of_a_kind(self):
     hand = Hand()
     for i in range(4):
         hand.hand[i]._Die__face = 1
     for i in range(4, 5):
         hand.hand[i]._Die__face = 2
     self.assertEqual(Rules().four_of_a_kind(hand), 6)
Beispiel #12
0
 def test_three_of_a_kind(self):
     hand = Hand()
     for i in range(3):
         hand.hand[i]._Die__face = 1
     for i in range(3, 5):
         hand.hand[i]._Die__face = 2
     self.assertEqual(Rules().three_of_a_kind(hand), 7)
Beispiel #13
0
def parsing(filename):
    rules = Rules()
    try:
        file = open(filename, "r")
    except IOError:
        print "Error: Files does not exist"
        sys.exit(1)
    for line in file.readlines():
        sharp_pos = line.find("#")
        equal_pos = line.find("=")
        mark_pos = line.find("?")
        len_line = len(line)
        if (len_line == 1):
            continue
        else:
            if (equal_pos == 0):
                rules.set_initial_facts(line[1:])
            if (mark_pos == 0):
                rules.set_goals(line[1:])
            if (equal_pos < 0 and mark_pos < 0) or \
            (equal_pos > 0 and mark_pos < 0) :
                if (sharp_pos > 0):
                    rules.parse(line.split("#")[0])
                elif (sharp_pos < 0):
                    rules.parse(line)
    if (len(rules.goals) == 0):
        print "No Goal"
        sys.exit()
    if (len(rules.data) == 0):
        print "No Rule"
        sys.exit()
    rules.fact = ''.join(set(rules.fact))
    rules.initial_fact = ''.join(set(rules.initial_fact))
    rules.goals = ''.join(set(rules.goals))
    return rules
Beispiel #14
0
def findrule(ruletype="", attribute="", value=""):
    """
    debugging: find rules that have a certain ruleType and some 
    attribute-value pair
    
    Example: findrule("Concession", "nucleus", "usermodel_match") finds 
    rules of type 'Concession' where rule.nucleus == 'usermodel_match'.
    """
    rules = Rules().rule_dict
    matching_rules = {}

    if ruletype == "":
        for index, (name, rule) in enumerate(rules.iteritems()):
            if getattr(rule, attribute) is value:
                print "rule {0} - {1}:\n{2}".format(index, name, rule)
                matching_rules[name] = rule
    elif attribute == "":
        for index, (name, rule) in enumerate(rules.iteritems()):
            if rule.ruleType is ruletype:
                print "rule {0} - {1}:\n{2}".format(index, name, rule)
                matching_rules[name] = rule
    else:
        for index, (name, rule) in enumerate(rules.iteritems()):
            if rule.ruleType is ruletype and getattr(rule, attribute) is value:
                print "rule {0} - {1}:\n{2}".format(index, name, rule)
                matching_rules[name] = rule
    return matching_rules
Beispiel #15
0
 def __init__(self, size, session, scope, threads):
     super().__init__(size, session, scope, threads)
     self.autoresolve = False
     self.rules = Rules(size, FLAGS.connections)
     self.test_mode = False
     self.epsilon = 0.0
     self.board = None
Beispiel #16
0
def find_applicable_rules(messages):
    """    
    debugging: find out which rules are directly (i.e. without forming ConstituentSets first) applicable to your messages
    
    :type messages: ``list`` of ``Message``s or
                    ``Messages``
    """
    if type(messages) is list:  # is 'messages' a list of Message() instances?
        pass
    elif isinstance(messages, Messages):
        messages = messages.messages.values()

    for name, rule in Rules().rule_dict.iteritems():
        try:
            if rule.get_options(messages) != []:
                nuc_candidates = \
                    [rulename for (rulename, msg) in rule.nucleus]
                sat_candidates = \
                    [rulename for (rulename, msg) in rule.satellite]
                print "{0}: {1} - {2}, {3} - is directly applicable and results in \n\t{4}\n\n".format(
                    name, rule.ruleType, nuc_candidates, sat_candidates,
                    rule.get_options(messages))
        except:
            print "ERROR: Could not check if rule {0} is applicable. Possible solution: test if the rule's conditions are specified appropriately.\n\n".format(
                name)
Beispiel #17
0
 def select_scoring(self, hand):
     msg = "Choose which scoring to use "\
            "(leave empty to show available rows): "
     scoreboard_row = False
     score_saved = False
     while not scoreboard_row and not score_saved:
         scoreboard_row = input(msg)
         if scoreboard_row.strip() == "":
             self.show_scoreboard_points()
             scoreboard_row = False
             continue
         try:
             scoreboard_row = int(re.sub('[^0-9,]', '', scoreboard_row))
         except ValueError:
             print("You entered something other than a number.")
             print("Please try again")
             scoreboard_row = False
             continue
         if scoreboard_row > len(self.scoreboard_rows):
             print("Please select an existing scoring rule.")
             scoreboard_row = False
             continue
         else:
             score_saved = self.set_scoreboard_row_value(
                 int(scoreboard_row),
                 Rules().rules_map[int(scoreboard_row)](hand))
Beispiel #18
0
  def __init__(self,
               base_directory=None,
               verbose=False,
               being_tested=False,
               ignore_temp_rules=False,
               skip_tests=False):
    """Creates a new DepsChecker.

    Args:
      base_directory: OS-compatible path to root of checkout, e.g. C:\chr\src.
      verbose: Set to true for debug output.
      being_tested: Set to true to ignore the DEPS file at tools/checkdeps/DEPS.
    """
    self.base_directory = base_directory
    self.verbose = verbose
    self._under_test = being_tested
    self._ignore_temp_rules = ignore_temp_rules
    self._skip_tests = skip_tests

    if not base_directory:
      self.base_directory = os.path.abspath(
        os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', '..'))

    self.results_formatter = results.NormalResultsFormatter(verbose)

    self.git_source_directories = set()
    self._AddGitSourceDirectories()

    # Map of normalized directory paths to rules to use for those
    # directories, or None for directories that should be skipped.
    self.directory_rules = {}
    self._ApplyDirectoryRulesAndSkipSubdirs(Rules(), self.base_directory)
Beispiel #19
0
 def __init__(self, color):
     """
     Initializing the class with its color
     :param color: Disk.DARK or Disk.LIGHT
     """
     super().__init__(color)
     self.rules = Rules()
Beispiel #20
0
def test_calctime400():
    r = Rules("data/rules.txt")
    assert r.calc_time(0, 400) == (0, 60)
    assert r.calc_time(300, 400) == (540, 1200)
    assert r.calc_time(330, 400) == (597, 1320)
    assert r.calc_time(400, 400) == (728, 1620)
    assert r.calc_time(440, 400) == (728, 1620)
    def __init__(self):
        self.train_episodes = 20000  # max number of episodes to learn from
        self.gamma = 1  # future reward discount

        # Exploration parameters
        self.explore_start = 1.0  # exploration probability at start
        self.explore_stop = 0.01  # minimum exploration probability 0.01
        self.decay_rate = 0.0001  # exponential decay rate for exploration prob 0.00001

        # Network parameters
        self.hidden_size1 = 128  # number of units in each Q-network hidden layer 64
        self.hidden_size2 = 64
        self.hidden_size3 = 32
        self.learning_rate = 0.000005  # Q-network learning rate 0.00001

        # Memory parameters
        self.memory_size = 1000  # memory capacity
        self.batch_size = 64  # experience mini-batch size
        self.pretrain_length = self.batch_size * 8  # number experiences to pretrain the memory

        tf.reset_default_graph()
        self.QNetworkCard = QNetworkCard(name='main',
                                         hidden_size1=self.hidden_size1,
                                         hidden_size2=self.hidden_size2,
                                         hidden_size3=self.hidden_size3,
                                         learning_rate=self.learning_rate)

        self.memory = Memory(max_size=self.memory_size)

        self.s = interface_to_states()

        self.rules = Rules()

        self.reward_scale = 210  # lost solo schneider schwarz
Beispiel #22
0
def clean_rules(i_grammar):
    rules = i_grammar.rules
    print(rules.get_length(), "rules before")
    non_terminals = rules.getNonTerminalsList()
    prev_size = -1
    while len(non_terminals) != prev_size:
        prev_size = len(non_terminals)
        counter = Counter(non_terminals)
        to_remove = set()
        for key in counter:
            if counter[key] == 1 and key != "S":
                to_remove.add(key)
        new_rules = []
        for rule in rules.getRules():
            nts = rule.getNonTerminals()
            if any([nt in to_remove for nt in nts]):
                continue
            new_rules.append(rule)
        for rules_temp in rules.getConsommationRules().values():
            for rule in rules_temp:
                nts = rule.getNonTerminals()
                if any([nt in to_remove for nt in nts]):
                    continue
                new_rules.append(rule)
        rules = Rules(new_rules)
        non_terminals = rules.getNonTerminalsList()
    print(rules.get_length(), "rules after")
    return IndexedGrammar(rules)
Beispiel #23
0
def get_ISWC_grammar(relations, query):
    rules = []
    rules.append(EndRule("T", "epsilon"))
    rules.append(ProductionRule("S", "Finit", "end"))
    rules.append(ProductionRule("Finit", "F", query))
    for relation in relations:
        rules.append(DuplicationRule("F", relation, "F" + relation))
        rules.append(EndRule(relation, relation))
        rules.append(ProductionRule("F" + relation, "F", relation))
        rules.append(ConsommationRule(relation, "B", "Btemp" + relation))
        rules.append(DuplicationRule("Btemp" + relation,
                                     "Lleft" + relation,
                                     "B"))
        rules.append(DuplicationRule("Lleft", "L" + relation, relation))
        rules.append(ProductionRule("L" + relation, "L", relation))
        rules.append(ConsommationRule(relation, "L", "Ltemp" + relation))
        rules.append(DuplicationRule("Ltemp" + relation,
                                     "Lleft" + relation,
                                     "Lright" + relation))
        rules.append(DuplicationRule("Lleft" + relation,
                                     inverse(relation),
                                     "L"))
        rules.append(DuplicationRule("Lright" + relation,
                                     relation,
                                     "L" + relation))
    rules.append(EndRule("L", "epsilon"))
    rules.append(ConsommationRule("end", "B", "T"))
    rules.append(DuplicationRule("F", "B", "T"))
    rules = Rules(rules)
    return IndexedGrammar(rules)
 def __init__(self):
     """
     init method
     :return: None
     """
     self.r = Rules('domain')
     self.create_file()
Beispiel #25
0
    def __init__(self, parent=None):
        super(DeveloperInterface, self).__init__(parent)

        self.memRules = Rules("rulelist.json")
        self.variables = WorkMemory()

        self.inst_lbl = QLabel(
            "Escribe una sentencia antecedente->consecuente")
        self.id_lbl = QLabel("Id:")
        self.val_lbl = QLabel("Value:")
        self.solv_lbl = QLabel("No se ha llegado a una solucion")

        self.st_edit = QLineEdit()
        self.var_edit = QLineEdit()

        self.values = QComboBox()
        self.values.addItem("T")
        self.values.addItem("F")

        self.refresh_button = QPushButton("Evaluate!")
        self.propagate_button = QPushButton("Propagate!")

        self.statements = QPlainTextEdit()
        self.rules = QPlainTextEdit()
        self.solutions = QPlainTextEdit()

        self.statements.setReadOnly(True)
        self.rules.setReadOnly(True)
        self.solutions = QPlainTextEdit()

        self.hlayout = QHBoxLayout()
        self.hlayout.addWidget(self.st_edit)
        self.hlayout.addWidget(self.refresh_button)

        self.hlayout2 = QHBoxLayout()
        self.hlayout2.addWidget(self.id_lbl)
        self.hlayout2.addWidget(self.var_edit)
        self.hlayout2.addWidget(self.val_lbl)
        self.hlayout2.addWidget(self.values)
        self.hlayout2.addWidget(self.propagate_button)

        self.main_layout = QGridLayout()
        self.main_layout.addWidget(self.inst_lbl, 0, 0)
        self.main_layout.addLayout(self.hlayout, 1, 0)
        self.main_layout.addWidget(self.statements, 2, 0)
        self.main_layout.addLayout(self.hlayout2, 3, 0)
        self.main_layout.addWidget(self.rules, 4, 0)
        self.main_layout.addWidget(self.solv_lbl, 5, 0)
        self.main_layout.addWidget(self.solutions, 6, 0)

        self.refresh_button.clicked.connect(self.Evaluate)
        self.propagate_button.clicked.connect(self.Propagation)

        self.st_edit.setText("((a ^ b) ^ c) -> d")

        self.setLayout(self.main_layout)
        self.setWindowTitle("My first expert system")
        self.UpdateCache()
        self.PrintWorkMemory()
Beispiel #26
0
 def __init__(self, rules=None, *args, **kwargs):
     UniTable.__init__(self, *args, **kwargs)
     if not isinstance(rules, Rules):
         rules = Rules(rules)
     self._rules = rules
     self._rulearg = self.as_mapping()
     self._made = {}
     self._inprog = []
Beispiel #27
0
def test_calctime300():
    r = Rules("data/rules.txt")
    assert r.calc_time(0, 300) == (0, 60)
    assert r.calc_time(200, 300) == (353, 800)
    assert r.calc_time(220, 300) == (390, 880)
    assert r.calc_time(250, 300) == (447, 1000)
    assert r.calc_time(300, 300) == (540, 1200)
    assert r.calc_time(330, 300) == (540, 1200)
Beispiel #28
0
def test_calctime200():
    r = Rules("data/rules.txt")

    assert r.calc_time(0, 200) == (0, 60)
    assert r.calc_time(100, 200) == (176, 400)
    assert r.calc_time(150, 200) == (265, 600)
    assert r.calc_time(200, 200) == (353, 810)
    assert r.calc_time(220, 200) == (353, 810)
Beispiel #29
0
def deleteRule(rule):
    try:
        obj = Rules(ruleName=rule)
        response = jsonify({"Response": obj.delete()})
        return response
    except Exception as e:
        response = jsonify({"Response": False, "Reason": f"{e}"})
        return response
Beispiel #30
0
 def __init__(self, size, board, tree, network):
     self.network = network
     self.size = size
     self.tree = tree
     self.orig = board
     self.rules = Rules(size, FLAGS.connections)
     self.nr_moves = 0
     self.reinitialize()