Esempio n. 1
0
    def __init__(self, screen):
        self.width, self.height = pygame.display.get_surface().get_size()
        self.screen = screen
        self.sound_status = True
        self.bg = pygame.transform.scale(
            pygame.image.load(IMAGES_PATH + "bg.png"),
            (self.width, self.height))
        self.title = pygame.transform.scale(
            pygame.image.load(MENU_IMAGES_PATH + "titulo.png"),
            (int(self.width / 12 * 7), int(self.height / 5)))
        self.new_game = NewGame(screen, self.bg)
        self.controller = Controller(screen, self.sound_status)

        self.has_save = Data.has_save()
        self.continue_img = self.scale_it(
            pygame.image.load(MENU_IMAGES_PATH +
                              "continuar-jogo.png").convert_alpha())
        self.new_img = self.scale_it(
            pygame.image.load(MENU_IMAGES_PATH +
                              "novo-jogo.png").convert_alpha())
        self.leave_img = self.scale_it(
            pygame.image.load(MENU_IMAGES_PATH + "sair.png").convert_alpha())
        self.sound_img = pygame.transform.scale(
            pygame.image.load(MENU_IMAGES_PATH +
                              "sound_on.png").convert_alpha(), (215, 150))
 def reset(self, mode):
     self.controller = Controller(1000, 50, 50, 100)
     self.controller.go(350)
     self.init_hcell_count = HealthyCell.cell_count
     if mode == -1:
         self.verbose = False
     else:
         self.verbose = True
     self.total_dose = 0
     self.num_doses = 0
     self.radiation_h_killed = 0
     if self.dose_map is not None:
         self.dose_maps.append(
             (self.controller.tick - 350, np.copy(self.dose_map)))
         self.tumor_images.append(
             (self.controller.tick - 350, self.controller.observeDensity()))
     return self.observe()
    def __init__(self, obs_type, resize, reward, action_type, special_reward):
        """Constructor of the environment

        Parameters:
        obs_type : Type of observations provided to the agent (segmentation or densities)
        resize : True if the observations should be resized to 25 * 25 arrays
        reward : Type of reward function used ('dose' to minimize the total dose, 'killed' to maximize damage to cancer
                 cells while miniizing damage to healthy tissue and 'oar' to minimize damage to the Organ At Risk
        action_type : 'DQN' means that we have a discrete action domain and 'AC' means that it is continuous
        special_reward : True if the agent should receive a special reward at the end of the episode.
        """
        self.controller = Controller(1000, 50, 50, 100)
        self.controller.go(350)
        self.init_hcell_count = HealthyCell.cell_count
        self.obs_type = obs_type
        self.resize = resize
        self.reward = reward
        self.action_type = action_type
        self.special_reward = special_reward
        self.dose_map = None
Esempio n. 4
0
    def handle_mouseup(self):
        pos = pygame.mouse.get_pos()
        self.buttons["pressed"] = -1
        self.backbutton["pressed"] = False

        if in_bounds(pos, self.backbutton["bounds"]):
            self.on = False
        for index, button in enumerate(self.buttons["bounds"]):
            if in_bounds(pos, button):
                config.USERNAME = self.saves[index][0]
                Controller(self.screen).show()
Esempio n. 5
0
    def __init__(self):

        if App.instance:
            raise Exception

        GuiBoard.init()  # Initialize GuiBoard singleton

        App.instance = self

        self._running = False

        self.game = Controller()

        self.size = self.width, self.height = (1000, 1000)

        self.mode = App.Mode.title_screen

        self.button = Button(
            100, 100, 100, 100, "abc", App.button_font,
            lambda: print(crayons.cyan('clicked!')),
            Style(bg=(255, 255, 255), hbg=(0, 0, 0), tcolor=(255, 0, 0)))

        self.button.disabled = True

        self.exit = Button(
            0, 0, 200, 70, "Exit", App.button_font,
            lambda: App.instance.stop(),
            Style(bg=(233, 30, 99), hbg=(255, 96, 144), tcolor=(0, 0, 0)))

        self.exit.disabled = True

        s = Style((10, 123, 209), (10, 123, 209), (255, 255, 255))

        self.play_button = Button(300,
                                  450,
                                  400,
                                  125,
                                  "Play",
                                  App.title_screen_button_font,
                                  lambda: App.instance.set_mode(App.Mode.game),
                                  style=s)

        self.info_button = Button(300,
                                  600,
                                  400,
                                  125,
                                  "Info",
                                  App.title_screen_button_font,
                                  lambda: App.instance.set_mode(App.Mode.info),
                                  style=s)

        print(crayons.green('Instantiated App'))
class Application:
    """ """
    def __init__(self):
        self.controller = Controller()
        pass

    def execute(self):

        self.controller.initialise()
        self.controller.execute()
        self.controller.garbage()
        pass
Esempio n. 7
0
    def __init__(self, num_tokens, word_dim, hidden_dim,
                 stack_size, text_len, device):
        super(VQA, self).__init__()
        self.hidden_dim = hidden_dim
        self.num_tokens = num_tokens
        self.max_steps = stack_size - 1
        self.stack_size = stack_size
        self.text_len = text_len
        self.device = device

        self.token_embedding = nn.Embedding(num_tokens, word_dim)
        self.question_encoder = BiRnnEncoder(word_dim, hidden_dim)

        self.module_names = ["attend_key", "transfer_edge"]
        self.model_modules = [
            modules.AttendKey(),
            modules.TransferEdge(hidden_dim),
        ]
        for name, module in zip(self.module_names, self.model_modules):
            self.add_module(name, module)

        self.num_module = len(self.model_modules)
        self.controller = Controller(self.num_module, hidden_dim, self.max_steps, True, device)
class CellEnvironment(Environment):
    def __init__(self, obs_type, resize, reward, action_type, special_reward):
        """Constructor of the environment

        Parameters:
        obs_type : Type of observations provided to the agent (segmentation or densities)
        resize : True if the observations should be resized to 25 * 25 arrays
        reward : Type of reward function used ('dose' to minimize the total dose, 'killed' to maximize damage to cancer
                 cells while miniizing damage to healthy tissue and 'oar' to minimize damage to the Organ At Risk
        action_type : 'DQN' means that we have a discrete action domain and 'AC' means that it is continuous
        special_reward : True if the agent should receive a special reward at the end of the episode.
        """
        self.controller = Controller(1000, 50, 50, 100)
        self.controller.go(350)
        self.init_hcell_count = HealthyCell.cell_count
        self.obs_type = obs_type
        self.resize = resize
        self.reward = reward
        self.action_type = action_type
        self.special_reward = special_reward
        self.dose_map = None

    def get_tick(self):
        return self.controller.tick

    def init_dose_map(self):
        self.dose_map = np.zeros((50, 50), dtype=float)
        self.dataset = [[], [], []]
        self.dose_maps = []
        self.tumor_images = []

    def add_radiation(self, dose, radius, center_x, center_y):
        if dose == 0:
            return
        multiplicator = get_multiplicator(dose, radius)
        for x in range(50):
            for y in range(50):
                dist = math.sqrt((center_x - x)**2 + (center_y - y)**2)
                self.dose_map[x, y] += scale(radius, dist, multiplicator)

    def reset(self, mode):
        self.controller = Controller(1000, 50, 50, 100)
        self.controller.go(350)
        self.init_hcell_count = HealthyCell.cell_count
        if mode == -1:
            self.verbose = False
        else:
            self.verbose = True
        self.total_dose = 0
        self.num_doses = 0
        self.radiation_h_killed = 0
        if self.dose_map is not None:
            self.dose_maps.append(
                (self.controller.tick - 350, np.copy(self.dose_map)))
            self.tumor_images.append(
                (self.controller.tick - 350, self.controller.observeDensity()))
        return self.observe()

    def act(self, action):
        dose = action / 2 if self.action_type == 'DQN' else action[0] * 4 + 1
        rest = 24 if self.action_type == 'DQN' else int(
            round(action[1] * 60 + 12))
        if self.dose_map is not None:
            self.controller.grid.compute_center()
            x = self.controller.grid.center_x
            y = self.controller.grid.center_y
            tumor_radius = self.controller.grid.tumor_radius(
                self.controller.grid.center_x, self.controller.grid.center_y)
        pre_hcell = HealthyCell.cell_count
        pre_ccell = CancerCell.cell_count
        self.total_dose += dose
        self.num_doses += 1 if dose > 0 else 0
        self.controller.irradiate(dose)
        self.radiation_h_killed += (pre_hcell - HealthyCell.cell_count)
        if self.dose_map is not None:
            self.add_radiation(dose, tumor_radius, x, y)
            self.dataset[0].append(self.controller.tick - 350)
            self.dataset[1].append((pre_ccell, CancerCell.cell_count))
            self.dataset[2].append(dose)
            self.dose_maps.append(
                (self.controller.tick - 350, np.copy(self.dose_map)))
            self.tumor_images.append(
                (self.controller.tick - 350, self.controller.observeDensity()))
        p_hcell = HealthyCell.cell_count
        p_ccell = CancerCell.cell_count
        self.controller.go(rest)
        post_hcell = HealthyCell.cell_count
        post_ccell = CancerCell.cell_count
        reward = self.adjust_reward(dose, pre_ccell - post_ccell,
                                    pre_hcell - min(post_hcell, p_hcell))
        if self.verbose:
            print("Radiation dose :", dose, "Gy ", "remaining :", post_ccell,
                  "time =", rest, "reward=", reward)
        return reward

    def adjust_reward(self, dose, ccell_killed, hcells_lost):
        if self.special_reward and self.inTerminalState() or False:
            if self.end_type == "L" or self.end_type == "T":
                return -1
            else:
                if self.reward == 'dose':
                    return -dose / 400 + 0.5 - (self.init_hcell_count -
                                                HealthyCell.cell_count) / 3000
                else:
                    return 0.5 - (
                        self.init_hcell_count - HealthyCell.cell_count
                    ) / 3000  #(cppCellModel.HCellCount() / self.init_hcell_count) - 0.5 - (2 * hcells_lost/2500)
        else:
            if self.reward == 'dose' or self.reward == 'oar':
                return -dose / 400 + (ccell_killed - 5 * hcells_lost) / 100000
            elif self.reward == 'killed':
                return (ccell_killed - 5 * hcells_lost) / 100000

    def inTerminalState(self):
        if CancerCell.cell_count <= 0:
            if self.verbose:
                print("No more cancer")
            self.end_type = 'W'
            return True
        elif HealthyCell.cell_count < 10:
            if self.verbose:
                print("Cancer wins")
            self.end_type = "L"
            return True
        elif self.controller.tick > 1550:
            if self.verbose:
                print("Time out!")
            self.end_type = "T"
            return True
        else:
            return False

    def nActions(self):
        if self.action_type == 'DQN':
            return 9
        elif self.action_type == 'DDPG':
            return [[0, 1], [0, 1], [0, 1]] if self.tumor_radius else [[0, 1],
                                                                       [0, 1]]

    def end(self):
        del self.controller

    def inputDimensions(self):
        if self.resize:
            tab = [(1, 25, 25)]
        else:
            tab = [(1, 50, 50)]
        return tab

    def observe(self):
        if self.obs_type == 'densities':
            cells = (np.array(self.controller.observeDensity(),
                              dtype=np.float32)) / 100.0
        else:
            cells = (np.array(self.controller.observeSegmentation(),
                              dtype=np.float32) +
                     1.0) / 2.0  #  Obs from 0 to 1
        if self.resize:
            cells = cv2.resize(cells,
                               dsize=(25, 25),
                               interpolation=cv2.INTER_CUBIC)
        return [cells]

    def summarizePerformance(self, test_data_set, *args, **kwargs):
        print(test_data_set)
Esempio n. 9
0
 def __init__(self):
     self.controller = Controller()
     pass
Esempio n. 10
0
class Menu:
    def __init__(self, screen):
        self.width, self.height = pygame.display.get_surface().get_size()
        self.screen = screen
        self.bg = pygame.transform.scale(pygame.image.load(IMAGES_PATH + "bg.png"), (self.width, self.height))
        self.title = pygame.transform.scale(pygame.image.load(MENU_IMAGES_PATH + "titulo.png"),
                                            (int(self.width / 12 * 7), int(self.height / 5)))
        self.new_game = NewGame(screen, self.bg)
        self.controller = Controller(screen)

        self.has_save = Data.has_save()
        self.continue_img = self.scale_it(pygame.image.load(MENU_IMAGES_PATH + "continuar-jogo.png").convert_alpha())
        self.new_img = self.scale_it(pygame.image.load(MENU_IMAGES_PATH + "novo-jogo.png").convert_alpha())
        self.leave_img = self.scale_it(pygame.image.load(MENU_IMAGES_PATH + "sair.png").convert_alpha())
        self.sound_img = pygame.transform.scale( pygame.image.load(MENU_IMAGES_PATH + "sound_on.png").convert_alpha(), (215, 150))

    def change_sound_status(self):
        if self.controller.sound_status == True:
            self.sound_img = pygame.transform.scale(pygame.image.load(MENU_IMAGES_PATH + "sound_off.png").convert_alpha(), (215, 150))
            self.controller.change_sound_status()
        elif self.controller.sound_status == False:
            self.sound_img = pygame.transform.scale(pygame.image.load(MENU_IMAGES_PATH + "sound_on.png").convert_alpha(), (215, 150))
            self.controller.change_sound_status()

    def sound(self, x, y):
        """Shows sound button"""
        self.screen.blit(self.sound_img, (x, y))

    def continue_g(self, x, y):
        """Shows 'continuar' button"""
        c = Control_character()
        c.get_character('U')
        self.screen.blit(self.continue_img, (x, y))

    def new_g(self, x, y):
        """Shows 'Novo Jogo' button"""
        self.screen.blit(self.new_img, (x, y))

    def leave_g(self, x, y):
        """Shows 'Sair' button"""
        self.screen.blit(self.leave_img, (x, y))

    def show(self):
        """Show menu."""
        self.screen.blit(self.bg, (0, 0))
        self.screen.blit(self.title, (self.width / 2 - self.title.get_width() / 2, 50))
        if self.has_save:
            self.continue_g(self.width / 3, self.height / 5 * 2)
        self.new_g(self.width / 3, self.height / 5 * 3)
        self.leave_g(self.width / 3, self.height / 5 * 4)
        self.sound(1050, 550)

    def press_continue(self):
        """Changes 'continuar' image to its pressed version."""
        self.continue_img = self.scale_it(
            pygame.image.load(MENU_IMAGES_PATH + "continuar-jogo-pressed.png").convert_alpha())

    def drop_continue(self):
        """Changes 'continuar' image to its unpressed version."""
        if self.has_save:
            LoadGame(self.screen).show()

    def press_new(self):
        """Changes 'Novo jogo' image to its pressed version."""
        self.new_img = self.scale_it(pygame.image.load(MENU_IMAGES_PATH + "novo-jogo-pressed.png").convert_alpha())

    def drop_new(self):
        """Changes 'Novo jogo' image to its unpressed version. And go to person creation."""
        result = self.new_game.show()
        self.has_save = Data.has_save()

        if result == "created":
            self.controller.show()

    def press_leave(self):
        """Changes 'Sair' image to its pressed version."""
        self.leave_img = self.scale_it(pygame.image.load(MENU_IMAGES_PATH + "sair-pressed.png").convert_alpha())

    def drop_leave(self):
        """Changes 'Novo jogo' image to its unpressed version and quit game."""
        pygame.quit()
        exit()

    def scale_it(self, img):
        """Adjust buttons to be a third of screen with 100 oh height."""
        return pygame.transform.scale(
            img,
            (int(self.width / 3), 100))

    def detect_press(self, pos):
        """Detect presses on buttons."""

        x, y = pos
        if (self.width / 3 <= x <= self.width / 3 + self.continue_img.get_width() and
                self.height / 5 * 2 <= y <= self.height / 5 * 2 + self.continue_img.get_height()):
            self.press_continue()

        elif (self.width / 3 <= x <= self.width / 3 + self.new_img.get_width() and
              self.height / 5 * 3 <= y <= self.height / 5 * 3 + self.new_img.get_height()):
            self.press_new()

        elif (self.width / 3 <= x <= self.width / 3 + self.leave_img.get_width() and
              self.height / 5 * 4 <= y <= self.height / 5 * 4 + self.leave_img.get_height()):
            self.press_leave()

    def detect_drop(self, pos):
        """Detect drop on buttons."""
        self.reset_imgs()
        x, y = pos
        if (self.width / 3 <= x <= self.width / 3 + self.continue_img.get_width() and
                self.height / 5 * 2 <= y <= self.height / 5 * 2 + self.continue_img.get_height()):
            self.drop_continue()
        elif (self.width / 3 <= x <= self.width / 3 + self.new_img.get_width() and
              self.height / 5 * 3 <= y <= self.height / 5 * 3 + self.new_img.get_height()):
            self.drop_new()
        elif (1050 <= x <=1050+self.sound_img.get_width() and 
               550 <= y <= 550+self.sound_img.get_height()):
            self.change_sound_status()
        elif (self.width / 3 <= x <= self.width / 3 + self.leave_img.get_width() and
              self.height / 5 * 4 <= y <= self.height / 5 * 4 + self.leave_img.get_height()):
            self.drop_leave()

    def reset_imgs(self):
        self.new_img = self.scale_it(pygame.image.load(MENU_IMAGES_PATH + "novo-jogo.png").convert_alpha())
        self.leave_img = self.scale_it(pygame.image.load(MENU_IMAGES_PATH + "sair.png").convert_alpha())
        self.continue_img = self.scale_it(pygame.image.load(MENU_IMAGES_PATH + "continuar-jogo.png").convert_alpha())