Пример #1
0
    def __init__(self):
        super().__init__(daemon=True)
        self.name = 'EngineThread'
        self.state = self.ENGINE_BOOT

        self.sit = Situation()
        self.stack = [self.sit]

        self.index = 0
        self.running = False
        self.usemillisec = True
        self.millisec = 1
Пример #2
0
def test_scan():
    earley = Earley('a')
    earley.rules_list = [Rule('U', 'S'), Rule('S', 'a')]
    earley.situations_dict[0].add(Situation('S', 'a', 0, 0))
    earley.scan(0, 'a')

    is_added = False
    to_add = Situation('S', 'a', 0, 1)
    for sit in earley.situations_dict[1]:
        if sit == to_add:
            is_added = True
            break

    assert is_added
Пример #3
0
def generate_trace(db_path):
    db = DataBase(db_path)

    t = Trace()
    s = Situation()

    # Robot/Operator moving status
    moving_topics = {
        "/safety/robot/moving": s.robot.is_moving,
        "/safety/operator/moving": s.operator.is_moving,
    }
    for c in moving_topics.values():
        t[c] = (0.0, False)
    for m in from_table(db, "movablestatus"):
        if m.topic in moving_topics:
            t[moving_topics[m.topic]] = (m.timestamp, m.is_moving == 1)

    # Collision occurrences
    t[s.collision.occurs] = (0.0, False)
    t[s.collision.force] = (0.0, 0.0)
    for m in from_table(db, "collisionevent"):
        if m.entity_id == "Operator-Tim":
            t[s.collision.occurs] = (m.timestamp, True)
            t[s.collision.force] = (m.timestamp, m.collision_force)
            t[s.collision.occurs] = (m.timestamp + 0.01, False)
            t[s.collision.force] = (m.timestamp + 0.01, 0.0)

    # LIDAR Measurements
    t[s.lidar.distance] = (0.0, float("inf"))
    for m in from_table(db, "float32"):
        if m.topic == "/lidar/digital/range":
            t[s.lidar.distance] = (m.timestamp, m.data)

    return t
Пример #4
0
    def complete(self, list_number):
        situations_to_insert = []
        for situation in self.situations_dict[list_number]:
            list_number_2 = situation.index
            if situation.point == len(situation.output):
                for situation_2 in self.situations_dict[list_number_2]:
                    sit = Situation(situation_2.input, situation_2.output, situation_2.index, situation_2.point + 1)
                    situations_to_insert.append(sit)

        for situation in situations_to_insert:
            self.add_situation(situation, list_number)
Пример #5
0
    def predict(self, list_number):
        situations_to_insert = []
        for situation in self.situations_dict[list_number]:
            if situation.point < len(situation.output):
                nonterminal = situation.output[situation.point]
                for rule in self.rules_list:
                    if rule.input == nonterminal:
                        sit = Situation(nonterminal, rule.output, list_number, 0)
                        situations_to_insert.append(sit)

        for situation in situations_to_insert:
            self.add_situation(situation, list_number)
Пример #6
0
def test_predict():
    earley = Earley('a')
    earley.rules_list = [Rule('U', 'S'), Rule('S', 'a')]
    earley.predict(0)

    is_added = False
    to_add = Situation('S', 'a', 0, 0)
    for sit in earley.situations_dict[0]:
        if sit == to_add:
            is_added = True
            break

    assert is_added
Пример #7
0
def find_situations(concerns):
    # management of the first concern
    intro_sit_file = open('data/fixed_texts/intro_situations.txt', "r")
    sm.my_print_file(intro_sit_file, FLAG)
    intro_sit_file.close()
    # replacement of * in the questions with the concern LEO is facing at the moment
    uncompleted_question = sm.choose_sentence("situations")
    question = sm.replace_a_star(uncompleted_question,
                                 concerns[0].get_concern())
    sm.my_print_string(question, FLAG)
    answer = input()
    new_answer, keywords_list = analyze_answer(answer)
    for keyword in keywords_list:
        situation = sm.complete_keywords(new_answer, keyword[0])
        concerns[0].add_situation(Situation(situation))
    return concerns, answer
Пример #8
0
def getClient_():
    c = Situation.getSituation()
    otherdict[c.projectExp] = 1
    otherdict['deadline'] = c.project.duration
    otherdict['cost'] = c._Client__cost
    otherdict['c_patientLevel'] = c._Client__patient_level
    otherdict['estimated_days_to_complete'] = c.project.duration - 8
    otherdict['project_deadline'] = c.project.duration - 12
    manager.addProject(c)
    global client_level1
    client_level1 = c
    dict_client = {}
    dict_client['Project_Type'] = ProjectExpand[c.projectExp].value
    dict_client['deadline'] = c.project.duration
    dict_client['cost'] = c._Client__cost
    dict_client['patient_level'] = c._Client__patient_level
    return dict_client
Пример #9
0
def makeCorpus(world, wordFile, objectFile):
    # Input: World object, filenames of word and object files
    # Output: Corpus as list of Situations
    corpus = []
    wf = open(wordFile, 'r')
    of = open(objectFile, 'r')

    wl = wf.readline()
    ol = of.readline()
    while (len(wl) != 0 and len(ol) != 0):
        wl = processLine(wl)
        ol = processLine(ol)

        words = [world.words_key.index(x) for x in wl.split(' ') if x != '']
        objects = [
            world.objects_key.index(x) for x in ol.split(' ') if x != ''
        ]
        corpus.append(Situation(words, objects))

        wl = wf.readline()
        ol = of.readline()
    return corpus
Пример #10
0
 def __init__(self, word):
     situation = Situation('U', 'S', 0, 0)
     self.situations_dict = {i: set() for i in range(len(word) + 1)}
     self.situations_dict[0].add(situation)
     self.word = word
Пример #11
0
 def scan(self, list_number, symbol):
     for situation in self.situations_dict[list_number]:
         if situation.output[situation.point] == symbol:
             sit = Situation(situation.input, situation.output, situation.index, situation.point + 1)
             self.add_situation(sit, list_number + 1)
Пример #12
0
from situation import Situation

_S = Situation()

_COLLISION_FORCE_THRESHOLD = 100

# Any contact between the robot and operator
contact_occurs = _S.collision.occurs.eventually()

# Any hazardous contact between the robot and operator
collision_occurs = (_S.collision.occurs & _S.collision.force >
                    _COLLISION_FORCE_THRESHOLD).eventually()

# Any contact due to the operator moving into a stopped robot
operator_collides = (_S.collision.occurs & ~_S.robot.is_moving).eventually()

# The robot stops within 250ms when an obstacle gets too close
_SAFETY_STOP_THRESHOLD = 0.75
robot_safety_stops = ((_S.lidar.distance < _SAFETY_STOP_THRESHOLD).implies(
    (~_S.robot.is_moving)
    | (~_S.robot.is_moving).eventually(hi=0.250))).always()

monitored_conditions = {
    "Contact between operator and robot": contact_occurs,
    "Collision between operator and robot": collision_occurs,
    "Operator collides with robot": operator_collides,
    "Robot performs safety stop": robot_safety_stops,
}
Пример #13
0
 def __init__(self) -> None:
     self.callback = None
     self.sit = Situation()
Пример #14
0
class Manual(object):
    def __init__(self) -> None:
        self.callback = None
        self.sit = Situation()

    def parse(self, content: str):
        lines = content.splitlines()

        for nr, line in enumerate(lines, 1):
            line = line.strip()
            if not line:
                # 去掉空行
                continue
            if line.startswith('#'):
                # 去掉注释
                continue

            line = Line(nr, line)
            if not line.moves:
                continue
            for move in line.moves:
                fpos, tpos = self.parse_move(line, move)
                result = self.sit.move(fpos, tpos)
                if not result:
                    self.invalid_manual(line, move)
                if callable(self.callback):
                    self.callback(fpos, tpos)

    def parse_move(self, line: Line, move: str):
        logger.debug("parse move %s", move)
        board = self.sit.board
        if self.sit.turn == Chess.RED:
            board = np.rot90(board, k=2)

        fpos = self.get_fpos(board, line, move)
        tpos = self.get_tpos(board, fpos, move)

        if self.sit.turn == Chess.RED:
            fpos = (8 - fpos[0], 9 - fpos[1])
            tpos = (8 - tpos[0], 9 - tpos[1])

        return fpos, tpos

    def invalid_manual(self, line: Line, move: str):
        raise Exception(f'棋谱第 {line.nr} 行 {move} 不合法')

    def get_fpos(self, board, line, move):
        if PATTERN1.match(move[:2]):
            chess = CHESSES[move[0]] | self.sit.turn
            pos = NUMBERS[move[1]] - 1
            type = 1

        elif PATTERN2.match(move[:2]):
            chess = CHESSES[move[1]] | self.sit.turn
            pos = NUMBERS[move[0]]
            type = 2
        else:
            self.invalid_manual()

        ctype = chess & Chess.CMASK
        logger.debug("chess %s pos %s", chess, pos)
        wheres = np.argwhere(board == chess)
        if len(wheres) == 1:
            return tuple(wheres[0])

        wheres = sorted(wheres, key=lambda e: (e[0], e[1]))

        if type == 1:
            result = []
            for where in wheres:
                if where[0] != pos:
                    continue
                result.append(tuple(where))
            if len(result) == 1:
                return result[0]
            if ctype in (Chess.ADVISOR, Chess.BISHOP):
                if move[2] == BACKWARD:
                    return result[-1]
                else:
                    return result[0]
            self.invalid_manual(line, move)
        else:
            columns = {}
            for where in wheres:
                columns.setdefault(where[0], [])
                columns[where[0]].append(where)
            for key in list(columns.keys()):
                if len(columns[key]) < 2:
                    del columns[key]
            columns = sorted(columns.items(), key=lambda e: e[0], reverse=True)
            if move[0] == '前':
                return tuple(columns[0][1][-1])
            elif move[0] == '中':
                return tuple(columns[0][1][-2])
            elif move[0] == '后':
                return tuple(columns[0][1][0])

            index = self.numbers[move[0]]
            counter = 1
            for idx, column in columns:
                column = list(column)
                column.reverse()
                for where in column:
                    if counter == index:
                        return tuple(where)
                    counter += 1

            self.invalid_manual(line, move)

    def get_tpos(self, board, fpos, move):
        pos = NUMBERS[move[3]]
        action = move[2]
        if action == '平':
            return (pos - 1, fpos[1])

        chess = board[fpos]
        ctype = chess & Chess.CMASK

        if ctype in (Chess.KING, Chess.ROOK, Chess.CANNON, Chess.PAWN):
            if move[2] == '进':
                return (fpos[0], fpos[1] + pos)
            else:
                return (fpos[0], fpos[1] - pos)

        if ctype == Chess.BISHOP:
            if pos in (1, 5, 9):
                return (pos - 1, 2)
            if action == '进':
                return (pos - 1, 4)
            else:
                return (pos - 1, 0)
        elif ctype == Chess.ADVISOR:
            if pos == 5:
                return (pos - 1, 1)
            if action == '进':
                return (pos - 1, 2)
            else:
                return (pos - 1, 0)
        else:
            # 马的情况
            offset0 = (pos - 1) - fpos[0]
            if abs(offset0) == 1:
                if action == '进':
                    offset1 = 2
                else:
                    offset1 = -2
            else:
                if action == '进':
                    offset1 = 1
                else:
                    offset1 = -1
            return (fpos[0] + offset0, fpos[1] + offset1)
Пример #15
0
class Engine(threading.Thread):

    ENGINE_BOOT = 0
    ENGINE_IDLE = 1
    ENGINE_BUSY = 2

    ENGINE_MOVE = 3
    ENGINE_INFO = 4

    NAME = '基础引擎'

    def __init__(self):
        super().__init__(daemon=True)
        self.name = 'EngineThread'
        self.state = self.ENGINE_BOOT

        self.sit = Situation()
        self.stack = [self.sit]

        self.index = 0
        self.running = False
        self.usemillisec = True
        self.millisec = 1

    def callback(self, type, data):
        pass

    @property
    def checkmate(self):
        return self.sit.result == Chess.CHECKMATE

    def setup(self):
        pass

    def close(self):
        pass

    def set_index(self, index):
        if index < 0:
            return
        if index >= len(self.stack):
            return
        # logger.debug(f"{index}, {len(self.stack)}")

        self.index = index
        self.sit = self.stack[self.index]

    def move(self, fpos, tpos):
        # logger.debug('start move stack %s index %s', self.stack, self.index)

        nidx = self.index + 1
        if nidx < len(self.stack) and (self.stack[nidx].fpos,
                                       self.stack[nidx].tpos) == (fpos, tpos):
            logger.debug("forward hint %s", self.sit.format_move(fpos, tpos))
            self.sit = self.stack[nidx]
            self.index = nidx
            result = self.sit.result
            return self.sit.result
        else:
            self.stack = self.stack[:self.index + 1]

        sit = copy.deepcopy(self.sit)

        result = sit.move(fpos, tpos)
        sit.result = result

        if not result:
            return result

        if result != Chess.INVALID:
            self.stack.append(sit)
            self.sit = sit
            self.index += 1
        else:
            self.sit.check = sit.check

        # logger.debug('finish move stack %s index %s', self.stack, self.index)

        return result

    def undo(self):
        # 悔棋

        # logger.debug('start undo stack %s index %s', self.stack, self.index)
        if self.index == 0:
            return False

        self.index -= 1

        self.sit = self.stack[self.index]

        logger.debug(self.sit)
        # logger.debug('finish undo stack %s index %s', self.stack, self.index)

        return True

    def redo(self):
        nidx = self.index + 1
        if nidx >= len(self.stack):
            return False

        self.index += 1
        self.sit = self.stack[self.index]
        return True

    def position(self, fen=None):
        return

    def go(self,
           depth=None,
           nodes=None,
           time=None,
           movestogo=None,
           increment=None,
           opptime=None,
           oppmovestogo=None,
           oppincrement=None,
           draw=None,
           ponder=None):
        return
Пример #16
0
def main():
    # コマンドライン引数を読む
    args = read_args()

    # confファイルの読み込み
    conf = configparser.ConfigParser()
    conf.read('./setting.ini', 'UTF-8')

    # log設定
    logging.basicConfig(level=logging.DEBUG,
                        format="%(relativeCreated)08d[ms] - %(name)s - %(levelname)s - %(processName)-10s - %(threadName)s -\n*** %(message)s",
                        filename="log/app.log",
    )

    # 歩きスマホ人数
    arukisumaho_num = 0
    # 人数
    person_num = 0

    if args.img:
        img = abspath(args.img)
    else:
        # 画像ファイル名を設定
        basename = datetime.now().strftime("%Y%m%d-%H%M%S")
        img = "./media/"+basename+".jpg"

        # 画像を撮影
        wc = Webcam(conf.get("webcam", 'ip') ,
                    conf.get("webcam", 'port') ,
                    conf.get("webcam", 'user') ,
                    conf.get("webcam", 'password')
        )
        wc.setup_basic_auth()
        wc.take_picture(img)

    # 写真が存在しない場合終了する
    if not exists(img):
        print('画像がないよ')
        return

    # インスタンス作成
    situation = Situation()
    pm = ProjectionMapping(
        conf.get("vpt", 'ip') ,
        conf.getint("vpt", 'port')
        )

    # 最初に車の動画を流す
    pm.waiting()

    while True:
        if not args.img:
            wc.take_picture(img)
        situation.recognize(img)
        person_num = situation.get_person_num()
        arukisumaho_num = situation.get_arukisumaho_num()
        print('検出された人数: %d' % person_num)
        print('歩きスマホ人数: %d' % arukisumaho_num)

        try :
            # 歩きスマホいる場合
            if arukisumaho_num >= 1:
                pm.arukisumaho()
                sleep(10) # TODO : 動画時間入れる
                pm.waiting()
            else:
                # 歩行者が大勢いる場合
                if person_num > 1:
                    pm.wide_cross()
                    sleep(10) # TODO : 動画時間入れる
                    pm.waiting()
                # 歩行者ひとりいる場合
                elif person_num == 1:
                    pm.normal_cross()
                    sleep(10) # TODO : 動画時間入れる
                    pm.waiting()
                # 歩行者がいない場合
                else:
                    sleep(3)
                    pass

        except KeyboardInterrupt:
            pm.waiting()