def decide_action(self, trajectory_me, trajectory_you, subgoals,
                      obstacles):
        utility_me = []
        utility_you = []
        utility = []

        s_me = trajectory_me[-1]  # 真の位置
        s_you = trajectory_you[-1]
        prev_s_me = trajectory_me[-2]  # 真の位置
        prev_s_you = trajectory_you[-2]
        subgoal = subgoals
        obstacle = obstacles

        grid_points_me = self.making_grid(self.num_grid_x, self.num_grid_y,
                                          self.search_range_x,
                                          self.search_range_y)
        grid_points_you = self.making_grid(self.num_grid_x, self.num_grid_y,
                                           self.search_range_x,
                                           self.search_range_y)

        # 予測位置を中心としたグリッドを作成
        next_s_me = self.linear_extrapolation(trajectory_me)
        grid_points_me = self.making_grid(self.num_grid_x, self.num_grid_y,
                                          self.search_range_x,
                                          self.search_range_y)
        # 予測位置を中心としたグリッドを作成
        next_s_you = self.linear_extrapolation(trajectory_you)
        grid_points_you = self.making_grid(self.num_grid_x, self.num_grid_y,
                                           self.search_range_x,
                                           self.search_range_y)

        grid_points_me = grid_points_me + next_s_me.p
        grid_points_you = grid_points_you + next_s_you.p

        #    for next_p_me in grid_points_me:
        each_other_p = list(itertools.product(grid_points_you, grid_points_me))
        for next_p_you, next_p_me in each_other_p:
            next_d_me = next_p_me - s_me.p
            next_d_you = next_p_you - s_you.p
            states_me = States(prev_s_me, s_me,
                               AgentState(next_p_me, next_d_me))
            states_you = States(prev_s_you, s_you,
                                AgentState(next_p_you, next_d_you))
            u_me, u_you = self.calculation_utility(states_me, states_you,
                                                   subgoal, obstacle)
            utility_me.append(u_me)
            utility_you.append(u_you)
            utility.append(u_me + u_you)

            #                1ステップの全グリッドのutilityを持つリスト

        utility = np.array(utility)

        #        utility_color_map(utility, self.num_grid_x, self.num_grid_y, "utility")

        predicted_p_you, predicted_p_me = each_other_p[utility.argmax()]
        return predicted_p_me
Beispiel #2
0
    def __init__(self, generateFunc, Yesterday):
        self.df = generateFunc[0]
        self.stateOfDay = generateFunc[1]
        self.MoversList = generateFunc[2]
        self.YesterdayPatients = Yesterday
        s = States()
        self.deathRate = s.returnConfig("Rates", "deathRate", float)
        self.daysFromLimbo = s.returnConfig(
            "Days", "daysUntilLimboDieDuetoLackOfBeds", int)
        self.numberOfBeds = s.returnConfig("SampleDefaults", "numberOfBeds",
                                           int)
        self.deathsLackBed = s.returnConfig("Rates", "deathsDueToLackOfBeds",
                                            float)
        self.hospitalRate = s.returnConfig("Rates", "hospitalizationRate",
                                           float)
        self.hospitalRateICU = s.returnConfig("Rates", "deathRateForICU",
                                              float)
        self.dayUntilCuredCovid = s.returnConfig("Days",
                                                 "dayUnitlCuredIfPositive",
                                                 int)
        self.daysUnitlCuredHos = s.returnConfig("Days",
                                                "dayUnitlCuredIfInHospital",
                                                int)

        self.xlimit = s.returnConfig("SampleDefaults", "xlimit", int)
        self.ylimit = s.returnConfig("SampleDefaults", "ylimit", int)
        self.distanceLimit = s.returnConfig("SampleDefaults", "distance",
                                            float)
Beispiel #3
0
def run_game():
    """ initialize """
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    event = pygame.event.poll()

    # add music
    pygame.mixer.music.load("music.mp3")
    pygame.mixer.music.play(3, 0)
    pygame.mixer.music.set_volume(0.3)
    pygame.display.set_caption("alien_invasion_game")

    play_button = Button(settings, screen, "Play")
    states = States(settings)
    records = record(settings, screen, states)
    background_color = (0, 0, 0)

    player = Player(settings, screen)
    bullets = Group()
    aliens = Group()
    gf.fleet(settings, screen, player, aliens)
    while True:
        gf.incident(settings, screen, states, records, play_button, player, aliens, bullets)
        if states.game_active:
            player.update()
            gf.more_bullets(settings, screen, states, records, player, aliens, bullets)
            gf.new_aliens(settings, screen, states, records, player, aliens, bullets)
        gf.new_screen(settings, screen, states, records, player, aliens, bullets, play_button)
Beispiel #4
0
    def __init__(self):
        if self.game_is_inited is False:
            pygame.init()
            pygame.display.set_caption(Config.TITLE)

            self.main_window = pygame.display.set_mode(
                (Config.WIDTH, Config.HEIGHT))
            Sounds.background_sound.play(loops=-1)  # Фоновая музыка
            self.game_is_inited = True

        self.clock = pygame.time.Clock()
        self.background = SpriteBackGround()
        self.player = PlayerSpaceship()
        self.states = States()

        # Группа для всех спрайтов, их я буду обновлять и отрисовывать
        self.all_sprites = pygame.sprite.Group()

        # Группы для проверки коллизий
        self.lasers = pygame.sprite.Group()  # Выстрелы из корабля (лазеры)
        self.powerups = pygame.sprite.Group()  # Бафы

        # Создаю метеориты
        self.meteorites = pygame.sprite.Group()
        for _ in range(Config.TOTAL_METEORITES):
            tmp_meteorite = Meteorite()
            self.meteorites.add(tmp_meteorite)
            self.all_sprites.add(tmp_meteorite)

        self.events = Events(self)
        self.main_loop()  # Запускаю main loop
Beispiel #5
0
 def __init__(self, df, path):
     self.path = path
     self.fig, self.axs = plt.subplots(2, figsize=(10, 8))
     self.fig.suptitle('Covid-19 Epidemic Sample Model', fontsize=16)
     self.ld = [
         'Healthy', 'Covid-19(+)', 'Hospitalized', 'Cured', 'Self Cured',
         'Death Toll', 'Limbo', 'Total Cured'
     ]
     self.df = df[0]
     self.stateOfDay = df[1]
     self.MoversList = df[2]
     self.state = States()
     self.dayLimit = self.state.returnConfig('SampleDefaults', 'dayLimit',
                                             int)
     self.x = self.state.returnConfig('SampleDefaults', 'xLimit', int)
     self.y = self.state.returnConfig('SampleDefaults', 'yLimit', int)
     self.groupsize = self.state.returnConfig('SampleDefaults', 'groupSize',
                                              int)
     self.sampleSize = self.state.returnConfig('SampleDefaults',
                                               'sampleSize', float)
     self.distance = self.state.returnConfig('SampleDefaults', 'distance',
                                             float)
     self.beds = self.state.returnConfig('SampleDefaults', 'numberOfBeds',
                                         float)
     self.distanceLimit = self.state.returnConfig("SampleDefaults",
                                                  "distance", float)
Beispiel #6
0
 def _initialize(self, atoms):
     """ Initialization of hotbit. """
     if not self.init:
         self.set_text(self.txt)
         self.timer = Timer('Hotbit', txt=self.get_output())
         self.start_timing('initialization')
         self.el = Elements(self, atoms)
         self.ia = Interactions(self)
         self.st = States(self)
         self.rep = Repulsion(self)
         self.pp = PairPotential(self)
         if self.get('vdw'):
             if self.get('vdw_parameters') is not None:
                 self.el.update_vdw(self.get('vdw_parameters'))
             setup_vdw(self)
         self.env = Environment(self)
         pbc = atoms.get_pbc()
         # FIXME: gamma_cut -stuff
         #if self.get('SCC') and np.any(pbc) and self.get('gamma_cut')==None:
         #    raise NotImplementedError('SCC not implemented for periodic systems yet (see parameter gamma_cut).')
         if np.any(pbc) and abs(
                 self.get('charge')) > 0.0 and self.get('SCC'):
             raise AssertionError('Charged system cannot be periodic.')
         self.flush()
         self.flags = {}
         self.flags['Mulliken'] = False
         self.flags['DOS'] = False
         self.flags['bonds'] = False
         self.flags['grid'] = False
         self.stop_timing('initialization')
     self.el.set_atoms(atoms)
     if not self.init:
         self.init = True
         self.greetings()
Beispiel #7
0
    def __init__(self):

        s = States()
        self.groupSize = s.returnConfig("SampleDefaults", "groupSize", int)
        self.state = s.status
        self.colors = s.stateColors
        self.sampleSize = s.returnConfig("SampleDefaults", "sampleSize", float)
        self.x = s.returnConfig("SampleDefaults", "xLimit", int)
        self.y = s.returnConfig("SampleDefaults", "yLimit", int)
    def forward(self, x, state_old):
        states = States(state_old)
        x = self.bn(x)
        x = self.act(x)
        if self.pad is not None:
            #x = self.pad(x)
            pad = self.pad
            if pad[0] > 0:
                #save last times to use on next iter for left padding
                x = states.pad_left(x, pad[0], 3)
                pad = (0, ) + pad[1:]
            x = torch.nn.functional.pad(x, pad, mode='constant', value=0)

        x = self.conv(x)
        return x, states.state
Beispiel #9
0
def run_game():
    # Initialize game and create a screen object.
    pygame.init()
    ai_settings = Settings()
    states = States()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Make the Play button.
    play_button = Button(ai_settings, screen, "Play")

    # Create an instance to store game statistics and create a scoreboard..
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Set the background color.
    bg_color = (ai_settings.bg_color)

    # Make a ship, a group of bullets, and a group of aliens.
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets, states)

        if not states.paused:
            if stats.game_active:
                ship.update()
                gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                                  bullets)
                gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                                 bullets)

        gf.update_screen(ai_settings, stats, screen, sb, ship, aliens, bullets,
                         play_button)
	def __init__(self, day, generateFunc, processFunc, plotFunc, path):
		self.day = day
		self.path = path
		self.s = States()
		self.dayLimit = self.s.returnConfig('SampleDefaults', 'dayLimit', int)
		self.x = self.s.returnConfig('SampleDefaults', 'xLimit', int)
		self.y = self.s.returnConfig('SampleDefaults', 'yLimit', int)
		self.groupsize = self.s.returnConfig('SampleDefaults', 'groupSize', int)
		self.sampleSize = self.s.returnConfig('SampleDefaults', 'sampleSize', float)
		self.distance = self.s.returnConfig('SampleDefaults', 'distance', float)
		self.beds = self.s.returnConfig('SampleDefaults', 'numberOfBeds', float)
		logfile = f"{self.path}/{self.s.returnConfig('SampleDefaults', 'logfile', str)}"
		self.logFile = open(logfile, "w+")
		self.distanceLimit = self.s.returnConfig("SampleDefaults", "distance", float)
		self.generateData = generateFunc
		self.stateOfDay = self.generateData[1]
		self.MoversList = self.generateData[2]
		self.YesterdayPatients = list(self.generateData[0]['State'])
		self.startProcess = processFunc
		self.plotData = plotFunc
    def forward(self, x, state_old):
        states = States(state_old)

        for m in self.bd:
            x_add, state = m(x, states.state_old)
            states.update(state)
            x = torch.cat([x, x_add], 1)
        x, state = self.bd_out(x, states.state_old)
        states.update(state)

        if self.sa is None:
            return x, states.state

        #apply multihead self attension module
        #[B,C,F,T]
        x_add, state = self.sa(x, state_old=states.state_old)
        states.update(state)

        x = torch.cat([x, x_add], 1)

        x, state = self.sa_out(x, states.state_old)
        states.update(state)

        return x, states.state
Beispiel #12
0
    args = parser.parse_args()
    puzzle, size = parse_puzzle(args.file)
    if not check_puzzle(puzzle, size):
        print("Error")
        exit()

    goal = make_goal(size)

    if not solvable(puzzle, goal, size):
        print("This puzzle is not solvable")
        exit()
    else:
        print("This puzzle is solvable\n")

    heuristic, algo = choice_algo()
    states = States()
    Node.size = size
    Node.heuristic_g = Heuristic(size, goal, heuristic)
    start_node = Node(puzzle)

    if start_node.grid == goal:
        solution = [puzzle]
        states.total_open = 1
        states.max_rep = 1
        print_states(solution, states)
        exit()

    if algo == Algo.IDASTAR:
        solution = ida_star(start_node, states, goal)
    else:
        solution = bfs(start_node, states, goal)
Beispiel #13
0
from telebot import TeleBot
import config
from bot import bot
from states import States
import users_controller
import parse
from time import sleep

state_handler = States(bot)


@bot.message_handler(commands=['start'])
def start_handler(message):
    try:
        user = users_controller.get_user(message.chat.id)
        if user is None:
            users_controller.create_user(message)
        else:
            users_controller.update_state(message.chat.id, 'start')

        state_handler.handle_states(message, first_entry=True)
    except Exception as e:
        print('[ERROR]: {}'.format(e))


@bot.message_handler(content_types=['text'])
def handle_text(message):
    try:
        state_handler.handle_states(message)
    except Exception as e:
        print('[ERROR]: {}'.format(e))
Beispiel #14
0
df = pandas.read_csv("50_states.csv")

# Global list creation
STATES_NAME = []
STATES_X = []
STATES_Y = []

# Append data from csv into list
for i in range(len(df)):
    STATES_NAME.append(df["state"][i])
    STATES_X.append(df["x"][i])
    STATES_Y.append(df["y"][i])

# State object creation
for i in range(len(df)):
    states = States(STATES_NAME[i], STATES_X[i], STATES_Y[i])

# Main loop
while GAME_STATE:
    screen.update()
    answer_state = (screen.textinput(
        title=f"{SCORE}/50", prompt="What's another state's name?")).title()

    # Quit Game & Save Remaining
    if answer_state == "Quit" or answer_state == "Exit" or answer_state == "Stop":
        with open("remaining_states.txt", mode="w") as file:
            file.write(states.exit())
        GAME_STATE = False

    # Increase score if true
    if states.guess(answer_state):
Beispiel #15
0
def game_run():
    file = r'activation.mp3'
    # Initialize
    pygame.mixer.init()
    # Load the file pf music
    pygame.mixer.music.load(file)
    pygame.mixer.music.play()

    # Initialize and create screen.
    pygame.init()
    setting = Setting()
    screen = pygame.display.set_mode(
        (setting.screen_width, setting.screen_height))
    pygame.display.set_caption("Aircraft war")

    # Create play button
    play_button = Button(setting, screen, 'Play', 200)
    help_button = Button(setting, screen, 'Help', 400)

    # Draw a rocket.
    rocket = Rocket(setting, screen)

    # Set a Group for bullets.
    bullets = Group()

    # Set a Group for alien bullets.
    alien_bullets = Group()

    # Set a Group for aliens.
    aliens = Group()

    # Create aliens.
    functions.create_aliens(setting, screen, rocket, aliens, alien_bullets)

    # Create States.
    states = States(setting)

    # Create Scoreboard.
    scoreboard = Scoreboard(setting, screen, states)

    # Create Textbox.
    textbox = Textbox(setting, screen)

    # Create Incidents.
    incidents = Group()

    # Create Background.
    BackGround = Background('background.jpg', [0, 0])

    # Main loop.
    while True:
        functions.respond_events(setting, screen, states, scoreboard, rocket,
                                 aliens, bullets, alien_bullets, play_button,
                                 help_button, textbox, incidents)
        if states.game_active:
            rocket.update_rocket()
            bullets.update(rocket)
            alien_bullets.update(setting)
            incidents.update(states)
            functions.update_bullets(setting, screen, states, scoreboard,
                                     rocket, aliens, bullets, alien_bullets)
            functions.update_aliens(setting, screen, states, scoreboard,
                                    rocket, aliens, bullets, alien_bullets,
                                    incidents)
            functions.update_alien_bullets(setting, screen, states, scoreboard,
                                           rocket, aliens, bullets,
                                           alien_bullets, incidents)
            functions.update_incidents(setting, screen, states, scoreboard,
                                       rocket, aliens, bullets, alien_bullets,
                                       incidents)
        functions.screen_update(setting, screen, states, scoreboard, rocket,
                                aliens, bullets, alien_bullets, play_button,
                                help_button, textbox, incidents)
        screen.fill([255, 255, 255])
        screen.blit(BackGround.image, BackGround.rect)
from passlib.handlers.pbkdf2 import pbkdf2_sha256

from states import States
from display import Display, InformationScreen, KeypadScreen, MessageScreen, SetupScreen
from gpio import Alarm, Keypad

config = configparser.ConfigParser()
config.read('config.ini')

updatesTopic = 'device/updates'
actionsTopic = 'device/actions'

states = States(
    default={
        'deviceId': config['DEVICE']['id'],
        'alarm_state': False,
        'arm_state': False,
        'door_state': False,
    })

code = []  # Used to store currently typed passcode
alarm = Alarm(states)  # Thread for handling alarm

# Display and Screens
display = Display()
information = InformationScreen(states)
setup = SetupScreen(states)
keyboard = KeypadScreen(code)


def is_setup() -> bool:
    def forward(self, x, state_old=None):

        B, C, F, _ = get_shape(x)

        # [B,C,F,T] -> [B,3C,F,T]
        qkv = self.linear_qkv(x)

        # [B,3C,F,T] -> [B,F,3C,T]
        qkv = qkv.transpose(1, 2)

        # [B,F,3C,T] -> 3*[B,F,C,T]
        query, key, value = qkv.chunk(3, dim=2)

        #[B,F,C,T] -> [B,F,C,attn_range+T]
        states = States(state_old)
        key = states.pad_left(key, self.attn_range[0], dim=3)
        value = states.pad_left(value, self.attn_range[0], dim=3)

        # [B, F, C, T] -> [BF, n_heads, k_channels, T]
        T_q = get_shape(query)[3]
        T_kv = get_shape(key)[3]
        assert C == self.n_heads * self.k_channels
        query = query.reshape(B * F, self.n_heads, self.k_channels, T_q)
        key = key.reshape(B * F, self.n_heads, self.k_channels, T_kv)
        value = value.reshape(B * F, self.n_heads, self.k_channels, T_kv)

        # transpose [BF, n_heads, k_channels, T] -> [BF, n_heads, T, k_channels]
        query = query.transpose(2, 3)
        key = key.transpose(2, 3)
        value = value.transpose(2, 3)

        assert self.attn_unroll > 0
        q_s = 0
        outputs = []
        while q_s < T_q:
            q_e = min(q_s + self.attn_unroll, T_q)
            kv_s = q_s
            kv_e = min(q_e + sum(self.attn_range), T_kv)
            if q_s == 0 and q_e == T_q:
                query_slice = query
            else:
                query_slice = query[:, :, q_s:q_e, :]
            if kv_s == 0 and kv_e == T_kv:
                key_slice = key
                value_slice = value
            else:
                key_slice = key[:, :, kv_s:kv_e, :]
                value_slice = value[:, :, kv_s:kv_e, :]
            scores = torch.matmul(query_slice, key_slice.transpose(
                -2, -1)) / math.sqrt(self.k_channels)

            # mask key scores that out of attn range
            q_n = q_e - q_s
            k_mn = 1 + sum(self.attn_range)
            mask = torch.ones(q_n,
                              k_mn,
                              dtype=scores.dtype,
                              device=scores.device)
            mask = torch.nn.functional.pad(mask, (0, q_n),
                                           mode='constant',
                                           value=0)
            mask = mask.reshape(-1)[:q_n * (k_mn + q_n - 1)]
            mask = mask.reshape(q_n, (k_mn + q_n - 1))
            mask = mask[:, :kv_e - kv_s]
            mask = mask.unsqueeze(0).unsqueeze(0)

            scores = scores * mask + -1e4 * (1 - mask)
            p_attn = torch.nn.functional.softmax(scores,
                                                 dim=3)  # [b, n_h, l_q, l_kv]

            output = torch.matmul(p_attn, value_slice)
            outputs.append(output)
            q_s = q_e

        output = torch.cat(outputs, 2) if len(outputs) > 1 else outputs[0]

        # [BF, n_h, T_q, d_k] -> [BF, n_h, d_k, T_q]
        output = output.transpose(2, 3)

        # [BF, n_h, d_k, T_q] -> [B, F, C, T_q]
        output = output.reshape(B, F, C, T_q)

        # [B, F, C, T] -> [B, C, F, T]
        output = output.transpose(1, 2)

        #[B, C, F, T] -> [B, Co, F, T]
        output = self.conv_o(output)

        return output, states.state
    def forward(self, x, state_old=None):

        states = States(state_old)

        tail_size = self.wnd_length - self.hop_length
        x_padded = states.pad_left(x, tail_size, 1)

        X = self.encode(x_padded)
        # [B,2,F,T]
        z = X

        #DOWN
        skips = []
        for b in self.blocks_down:

            z, state = b(z, states.state_old)
            states.update(state)

            skips.append(z)
            z = self.pool(z)

        #BOTTOM
        z, state = self.block_bottom(z, states.state_old)
        states.update(state)

        #UP
        for skip, conv_up, block_up in zip(reversed(skips), self.convs_up,
                                           self.blocks_up):
            z = torch.nn.functional.interpolate(z,
                                                scale_factor=2,
                                                mode='nearest')
            Fs = get_shape(skip)[-2]
            Fz = get_shape(z)[-2]
            if Fz != Fs:
                z = torch.nn.functional.pad(z, (0, 0, 0, 1), mode='replicate')
            z = torch.cat([z, skip], 1)

            pad = self.convs_up_pad
            if pad[0] > 0:
                z = states.pad_left(z, pad[0], 3)
                pad = (0, ) + pad[1:]
            z = torch.nn.functional.pad(z, pad, mode='constant', value=0)
            z = conv_up(z)

            z, state = block_up(z, states.state_old)
            states.update(state)

        X = states.pad_left(X, self.ahead, 3, shift_right=True)

        # [B,2,F,T] -> [B,F,T],[B,F,T] ->
        Mr, Mi = z[:, 0], z[:, 1]
        Xr, Xi = X[:, 0], X[:, 1]

        # mask in complex space
        Yr = Xr * Mr - Xi * Mi
        Yi = Xr * Mi + Xi * Mr

        #[B,F,T] + [B,F,T] -> [B,2,F,T]
        Y = torch.stack([Yr, Yi], 1)

        # decode and return only valid samples
        Y_paded = states.pad_left(Y, self.ahead_ifft, 3)
        y = self.decode(Y_paded)
        y = y[:, tail_size:-self.ahead_ifft * self.hop_length]

        assert not states.state_old
        return y, Y, states.state