Exemplo n.º 1
0
 def __init__(self,
              list_path,
              img_size=416,
              augment=1,
              multiscale=True,
              normalized_labels=True):
     with open(list_path, "r") as file:
         tmp = file.readlines()
     self.img_files = []
     for img_path in tmp:
         img_path = img_path.strip()
         if os.path.exists(img_path):
             self.img_files.append(img_path)
     print("图片总数:{}".format(len(self.img_files)))
     self.label_files = [
         path.replace("images",
                      "labels").replace(".png",
                                        ".txt").replace(".jpg", ".txt")
         for path in self.img_files
     ]
     self.img_size = img_size
     self.max_objects = 100
     self.augment = augment
     self.multiscale = multiscale
     self.normalized_labels = normalized_labels
     self.min_size = self.img_size - 3 * 32
     self.max_size = self.img_size + 3 * 32
     self.batch_count = 0
     self.grid = Grid(True, True, 1, 0, 0.5, 1, 1.0)
Exemplo n.º 2
0
    def start_game(self) -> None:
        """
        Initialize Grid object and starts game loop.
        """
        self.grid = Grid()
        self.display()
        self.screen.blit(
            self.fonts["text_font"].render("NEW GAME!", True,
                                           self.config['color']['dark']),
            (140, 375))
        pygame.display.update()

        time.sleep(1)
        self.grid.generate_twos(number_of_twos=2)
        self.display()
Exemplo n.º 3
0
    def __init__(self, iteration_name: str, step_no: int):
        """

        Args:
            iteration_name (str): Name of the iteration
            step_no (int): Number of the step
        """

        # Check input parameters
        if not isinstance(iteration_name, str):
            raise TypeError(
                f'Input parameter iteration_name must be of type string.')
        if not isinstance(step_no, int):
            raise TypeError(
                f'Input parameter step_no must be of type integer.')

        self.grid = Grid()  # Initialize Grid object
        self.name = iteration_name
        self.prefix = None
        self.computing_time = None
        self.time = None
        self.path = Path()
        self.step_no = step_no
        self.log = log.getLogger(
            f'{self.__class__.__name__}:{step_no}_{iteration_name}')

        self.log.debug(
            f'New iteration step initialized. name={self.name}; step_no={self.step_no}'
        )
Exemplo n.º 4
0
def generate_interp(ds, lat_bounds=(-56.9, 83.6)):
    lons = ds.longitude.values[:]
    lats = ds.latitude.values[:]

    lat_bounds_min, lat_bounds_max = lat_bounds
    index_filter = (lats<=lat_bounds_max) & (lats>=lat_bounds_min)
    lats = lats[index_filter]
    lons = lons[index_filter]

    diff_lons = np.diff(lons)
    diff_lats = np.diff(lats)

    d_lon, d_lat = np.min(np.abs(diff_lons[diff_lons!=0])), np.min(np.abs(diff_lats[diff_lats!=0]))
    d_lon = min(d_lon, d_lat)
    d_lat = d_lon
    lon_min, lat_min, lon_max, lat_max = lons.min(), lats.min(), lons.max(), lats.max()
    interp_lons, interp_lats = np.meshgrid(np.arange(lon_min, lon_max, d_lon), np.arange(lat_max, lat_min, -d_lat))
    
    points = np.array((lons, lats)).T
    values_index = np.arange(points.shape[0], dtype='int')
    interp_indexes = griddata(points, values_index, (interp_lons, interp_lats), method='nearest')

    interp_lons, interp_lats, interp_indexes = roll_grid(interp_lons, interp_lats, interp_indexes)
    grid = Grid(interp_lats, interp_lons, regular=True)
    
    return grid, interp_indexes, index_filter
Exemplo n.º 5
0
    def test_bot(self) -> None:
        """
        Tests if bot works as designed.
        """
        self.grid = Grid()
        self.bot.grid = self.grid
        search_move_list: List[Callable[[], bool]] = get_moves_list(self.grid)

        self.grid.generate_twos(number_of_twos=2)
        while not (self.grid.is_win() or self.grid.is_lose()):
            ind = self.bot()
            search_move_list[ind]()
            self.grid.generate_twos(number_of_twos=1)
            print(self.grid)

        self.assertTrue(self.grid.is_win())
        self.assertFalse(self.grid.is_lose())
Exemplo n.º 6
0
    def __init__(self,
                 list_path,
                 img_size=416,
                 augment=1,
                 multiscale=True,
                 normalized_labels=True):
        with open(list_path, "r") as file:
            self.img_files = file.readlines()

        self.label_files = [
            path.replace("images",
                         "labels").replace(".png",
                                           ".txt").replace(".jpg", ".txt")
            for path in self.img_files
        ]
        self.img_size = img_size
        self.max_objects = 100
        self.augment = augment
        self.multiscale = multiscale
        self.normalized_labels = normalized_labels
        self.min_size = self.img_size - 3 * 32
        self.max_size = self.img_size + 3 * 32
        self.batch_count = 0
        self.grid = Grid(True, True, 1, 0, 0.5, 1, 1.0)
Exemplo n.º 7
0
    def __init__(self) -> None:
        self.grid: Grid = Grid()

        self.action_space: gym.spaces.Discrete = \
            gym.spaces.Discrete(4)
        self.observation_space: gym.spaces.Box = \
            gym.spaces.Box(0, 1,
                           (self.grid.grid_size, self.grid.grid_size,
                            self.grid.grid_size * self.grid.grid_size),
                            dtype=np.int16)

        self.steps: int = 0
        self.max_steps: int = 10000
        self.max_illegal_moves: int = 10
        self.num_illegal_moves: int = 0
        self.illegal_move_reward: float = 0.0
        self.reward_range: Tuple[float, float] =\
            (0.0, self.grid.grid_size * self.grid.grid_size)
Exemplo n.º 8
0
    def search_for_one_move(self, search_grid: Grid, move_index: int) -> int:
        """
        Performs search for a given number. 'searches_per_moves' iterations are performed
        and then all the acquired scores are summed.

        Parameters
        ----------
        search_grid: Grid
            Grid for which current search will be performed.
        move_index: int
            Index in a list of a first move in a search.

        Returns
        -------
        int
            Sum of scores in all simulated games.
        """
        search_score: int = 0
        search_moves: List[Callable[[], bool]] = get_moves_list(search_grid)

        is_valid: bool = search_moves[move_index]()

        if not is_valid:
            return 0

        search_grid.generate_twos(number_of_twos=1)
        current_grid: np.ndarray = np.copy(search_grid.grid)
        current_score: int = search_grid.score
        for _ in range(self.searches_per_move):
            search_grid.grid = np.copy(current_grid)
            search_grid.score = current_score
            for _ in range(self.moves_per_search):
                if search_grid.is_win() or search_grid.is_lose():
                    break
                is_valid = make_random_move(search_moves)
                if is_valid:
                    search_grid.generate_twos(number_of_twos=1)
            search_score += search_grid.score

        return search_score
Exemplo n.º 9
0
    async def generate_grids(self):
        """
        Generates new `Grid`s for all clients
        :return:
        """
        if not self.playing:
            raise RuntimeError("Game not in progress!")
        name_generator = CommandNameGenerator()

        for slot in self.slots:
            g = Grid(name_generator)

            # Game modifier post processor if needed
            if self.game_modifier is not None:
                try:
                    self.game_modifier.grid_post_processor(g)
                except NotImplementedError:
                    pass

            slot.grid = g
Exemplo n.º 10
0
class ListDataset(Dataset):
    def __init__(self,
                 list_path,
                 img_size=416,
                 augment=1,
                 multiscale=True,
                 normalized_labels=True):
        with open(list_path, "r") as file:
            self.img_files = file.readlines()

        self.label_files = [
            path.replace("images",
                         "labels").replace(".png",
                                           ".txt").replace(".jpg", ".txt")
            for path in self.img_files
        ]
        self.img_size = img_size
        self.max_objects = 100
        self.augment = augment
        self.multiscale = multiscale
        self.normalized_labels = normalized_labels
        self.min_size = self.img_size - 3 * 32
        self.max_size = self.img_size + 3 * 32
        self.batch_count = 0
        self.grid = Grid(True, True, 1, 0, 0.5, 1, 1.0)

    def __getitem__(self, index):
        #import pdb
        #pdb.set_trace()
        if self.augment == 0:  # 不增强
            img, targets = self.load_img_target(index)
        elif self.augment == 1:  # 随机水平翻转
            img, targets = self.load_img_target(index)
            if np.random.random() < 0.5:
                img, targets = horisontal_flip(img, targets)
        elif self.augment == 2:  # GridMask
            img, targets = self.load_img_target(index)
            if np.random.random() < 0.5:
                img, targets = self.grid.__call__(img, targets)  # GridMask
        elif self.augment == 3:  # Mosaic
            if np.random.random() < 0.5:
                img, targets = self.load_mosaic(index)
            else:
                img, targets = self.load_img_target(index)
        else:  # 全部
            if np.random.random() < 0.5:
                img, targets = self.load_mosaic(index)
            else:
                img, targets = self.load_img_target(index)
            if np.random.random() < 0.5:
                img, targets = self.grid.__call__(img.float(),
                                                  targets)  # GridMask
            if np.random.random() < 0.5:
                img, targets = horisontal_flip(img.float(), targets)

        return img.float(), targets

    def load_img_target(self, index):
        #import pdb
        #pdb.set_trace()
        #img, labels = self.load_mosaic(index)
        # ---------
        #  Image
        # ---------

        img_path = self.img_files[index % len(self.img_files)].rstrip()
        print(img_path)
        # 添加
        #base_dir = '/home/aim/WorkSpace/my_workspace/PyTorch-YOLOv3/data/face_mask/JPEGImages'
        #img_path = os.path.join(base_dir, img_path)

        # Extract image as PyTorch tensor
        img = transforms.ToTensor()(Image.open(img_path).convert('RGB'))

        # Handle images with less than three channels
        if len(img.shape) != 3:
            img = img.unsqueeze(0)
            img = img.expand((3, img.shape[1:]))

        _, h, w = img.shape
        h_factor, w_factor = (h, w) if self.normalized_labels else (1, 1)
        # Pad to square resolution
        img, pad = pad_to_square(img, 0)
        _, padded_h, padded_w = img.shape

        # ---------
        #  Label
        # ---------

        label_path = self.label_files[index % len(self.img_files)].rstrip()

        targets = None
        if os.path.exists(label_path):
            boxes = torch.from_numpy(np.loadtxt(label_path).reshape(-1, 5))
            # Extract coordinates for unpadded + unscaled image
            x1 = w_factor * (boxes[:, 1] - boxes[:, 3] / 2)
            y1 = h_factor * (boxes[:, 2] - boxes[:, 4] / 2)
            x2 = w_factor * (boxes[:, 1] + boxes[:, 3] / 2)
            y2 = h_factor * (boxes[:, 2] + boxes[:, 4] / 2)
            # Adjust for added padding
            x1 += pad[0]
            y1 += pad[2]
            x2 += pad[1]
            y2 += pad[3]
            # boxes[:, 0] => class id
            # Returns (xc, yc, w, h)
            boxes[:, 1] = ((x1 + x2) / 2) / padded_w  # newer center x
            boxes[:, 2] = ((y1 + y2) / 2) / padded_h  # newer center y
            boxes[:, 3] *= w_factor / padded_w  # newer width
            boxes[:, 4] *= h_factor / padded_h  # newer height

            targets = torch.zeros((len(boxes), 6))
            targets[:, 1:] = boxes
        # Apply augmentations
        #if self.augment:
        #    if np.random.random() < 0.5:
        #        img, targets = horisontal_flip(img, targets)

        return img, targets

    def collate_fn(self, batch):
        imgs, targets = list(zip(*batch))
        # Remove empty placeholder targets
        targets = [boxes for boxes in targets if boxes is not None]
        # Add sample index to targets
        for i, boxes in enumerate(targets):
            boxes[:, 0] = i
        targets = torch.cat(targets, 0)
        # Selects new image size every tenth batch
        if self.multiscale and self.batch_count % 10 == 0:
            self.img_size = random.choice(
                range(self.min_size, self.max_size + 1, 32))
        # Resize images to input shape
        imgs = torch.stack([resize(img, self.img_size) for img in imgs])
        self.batch_count += 1
        return imgs, targets

    def __len__(self):
        return len(self.img_files) - 1
        #return 128

    def load_mosaic(self, index):
        # loads images in a mosaic

        labels4 = []
        s = self.img_size
        xc, yc = [int(random.uniform(s * 0.5, s * 1.5))
                  for _ in range(2)]  # mosaic center x, y
        xc, yc = s, s
        indices = [index] + [
            random.randint(0,
                           len(self.label_files) - 1) for _ in range(3)
        ]  # 3 additional image indices
        # 在可允许的范围之内,随机抽取4个indices (batchsize=16, [1, 0, 2, 4], [2, 0, 1, 4])
        for i, index in enumerate(indices):
            # Load image
            #img, target = self.load_img_target(index)
            #img = cv2.resize(img, (s, s))
            #img_path = self.img_files[index % len(self.img_files)].rstrip()
            #img = cv2.imread(img_path)
            #(h, w) = img.shape[:2]
            img, _, (h, w) = self.load_image(index)

            label_path = self.label_files[index % len(self.img_files)].rstrip()
            target = np.loadtxt(label_path).reshape(-1, 5)
            # place img in img4
            if i == 0:  # top left
                # 把新图像先设置成原来的4倍,到时候再resize回去,114是gray
                img4 = np.full((s * 2, s * 2, img.shape[2]),
                               114,
                               dtype=np.uint8)  # base image with 4 tiles
                x1a, y1a, x2a, y2a = max(xc - w, 0), max(
                    yc - h,
                    0), xc, yc  # xmin, ymin, xmax, ymax (new/large image)
                x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (
                    y2a -
                    y1a), w, h  # xmin, ymin, xmax, ymax (original/small image)
                # 回看ppt讲解
            elif i == 1:  # top right
                x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
                x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
            elif i == 2:  # bottom left
                x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
                x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, max(xc, w), min(
                    y2a - y1a, h)
            elif i == 3:  # bottom right
                x1a, y1a, x2a, y2a = xc, yc, min(xc + w,
                                                 s * 2), min(s * 2, yc + h)
                x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)

            img4[y1a:y2a, x1a:x2a] = img[y1b:y2b,
                                         x1b:x2b]  # img4[ymin:ymax, xmin:xmax]
            padw = x1a - x1b  # 有时边上还是灰的
            padh = y1a - y1b

            # Labels
            #x = self.label_files[index]
            x = target.copy()
            labels = x.copy()
            if x.size > 0:  # Normalized xywh to pixel xyxy format
                # 此时x是0-1,同时,label是[bbox_xc, bbox_yc, bbox_w, bbox_c]
                labels[:, 1] = w * (x[:, 1] - x[:, 3] / 2) + padw
                labels[:, 2] = h * (x[:, 2] - x[:, 4] / 2) + padh
                labels[:, 3] = w * (x[:, 1] + x[:, 3] / 2) + padw
                labels[:, 4] = h * (x[:, 2] + x[:, 4] / 2) + padh
            labels4.append(labels)

        # Concat/clip labels
        if len(labels4):
            # a = np.array([[1, 2], [3, 4]])
            # c = np.concatenate(a, axis=0)
            # c: [1, 2, 3, 4]
            labels4 = np.concatenate(labels4, 0)  # 0是dimension
            # np.clip(labels4[:, 1:] - s / 2, 0, s, out=labels4[:, 1:])  # use with center crop
            np.clip(labels4[:, 1:], 0, 2 * s,
                    out=labels4[:, 1:])  # use with random_affine

        labels4 = torch.from_numpy(labels4)

        targets = torch.zeros((labels4.shape[0], 6))
        targets[:, 1] = labels4[:, 0]
        targets[:, 2] = (labels4[:, 1] + labels4[:, 3]) / (4 * s)  # x
        targets[:, 3] = (labels4[:, 2] + labels4[:, 4]) / (4 * s)  # y
        targets[:, 4] = (labels4[:, 3] - labels4[:, 1]) / (4 * s)  # w
        targets[:, 5] = (labels4[:, 4] - labels4[:, 2]) / (4 * s)  # h

        # Augment
        # img4 = img4[s // 2: int(s * 1.5), s // 2:int(s * 1.5)]  # center crop (WARNING, requires box pruning)
        # img4, labels4 = random_affine(img4, labels4,
        #                             degrees=self.hyp['degrees'],
        #                             translate=self.hyp['translate'],
        #                             scale=self.hyp['scale'],
        #                             shear=self.hyp['shear'],
        #                             border=-s // 2)  # border to remove

        img4 = torch.from_numpy(np.transpose(img4, (2, 0, 1)))

        return img4, targets

    def load_image(self, index):
        # loads 1 image from dataset, returns img, original hw, resized hw
        path = self.img_files[index % len(self.img_files)].rstrip()
        print(path)
        img = cv2.imread(path)  # BGR
        assert img is not None, 'Image Not Found ' + path
        h0, w0 = img.shape[:2]  # orig hw
        r = self.img_size / max(h0, w0)  # resize image to img_size
        if r != 1:  # always resize down, only resize up if training with augmentation
            interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR
            img = cv2.resize(img, (int(w0 * r), int(h0 * r)),
                             interpolation=interp)
        return img, (h0, w0), img.shape[:2]  # img, hw_original, hw_resized
Exemplo n.º 11
0
# Postprocessing Abaqus simulation
abaqus_handler.set_file(
    f'output_file_{step_name}_void-ratio', actual_step['abaqus'].get_path() /
    f'{actual_step["abaqus"].get_prefix()}_void-ratio.csv')

# Read pore pressure from previous ended simulation stored in **_pore-pressure.csv and store those in actual step
# as grid values. Those can be used to generate randomly lowered pore pressure values.
void_ratio_import = abaqus_handler.engine.read_csv_file(
    file=abaqus_handler.get_file(f'output_file_{step_name}_void-ratio'),
    x_coord_row=0,
    y_coord_row=1,
    z_coord_row=2,
    values_row={'void_ratio': 3})

# Initiate a new temporary grid for imported pore pressure
pore_pressure_import_grid = Grid()
pore_pressure_import_grid.initiate_grid(void_ratio_import, 'void_ratio')

# Transform void ratio from imported grid to abaqus engine's grid
transformer = GridTransformer()
transformer.add_grid(actual_step['abaqus'].grid, 'abaqus')
transformer.add_grid(pore_pressure_import_grid, 'import')
transformer.find_nearest_neighbors('import', 'abaqus', 4)
transformer.transition('import', 'void_ratio', 'abaqus')

# Transform void ratio to porosity
data_dict = actual_step['abaqus'].grid.get_node_values('void_ratio')

for key, item in data_dict.items():
    data_dict[key] = item / (1 + item)
Exemplo n.º 12
0
    def __init__(self, config: dict) -> None:
        """
        Parameters
        ----------
        config: dict
            A JSON which contains configuration of the game (colors, sizes, coordinates etc.).
        """
        self.config: dict = config
        self.best_score: int = self.config["best_score"]
        self.grid_size: int = self.config['grid_size']
        self.grid: Grid = Grid()

        pygame.init()

        # pygame's attributes
        self.screen: pygame.surface.Surface = \
            pygame.display.set_mode((config['size'],
                                     config['size'] + self.config["header_height"]))

        self.fonts: Dict[str, pygame.font.Font] = {
            "text_font":
            pygame.font.SysFont(self.config['font'],
                                self.config['text_font_size'],
                                bold=True),
            "button_font":
            pygame.font.SysFont(self.config['font'],
                                self.config['button_font_size'],
                                bold=True),
            "title_font":
            pygame.font.SysFont(self.config['font'],
                                self.config['title_font_size'],
                                bold=True)
        }
        self.buttons: Dict[str, Button] = {
            "menu":
            Button(
                self.fonts["title_font"],
                ButtonColors(self.config["color"]["2048"],
                             self.config["color"]["2048"],
                             self.config["color"]["white"]),
                (10, 15, 150, 120)),
            "play":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config["color"]["play"],
                             self.config["color"]["64"],
                             self.config["color"]["black"]),
                (105, 400, 300, 45)),
            "monte_carlo":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config["color"]["play"],
                             self.config["color"]["64"],
                             self.config["color"]["black"]),
                (105, 500, 300, 45)),
            "reset":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config["color"]["play"],
                             self.config["color"]["64"],
                             self.config["color"]["black"]),
                (105, 250, 300, 45)),
            "current_score":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config['color']['score'],
                             self.config["color"]["64"],
                             self.config["color"]["white"]),
                (190, 15, 150, 60)),
            "best":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config['color']['score'],
                             self.config["color"]["64"],
                             self.config["color"]["white"]),
                (345, 15, 150, 60))
        }

        # initialize pygame
        pygame.display.set_caption('2048')
        icon: pygame.surface.Surface = pygame.transform.scale(
            pygame.image.load("images/game_icon.ico"), (32, 32))
        pygame.display.set_icon(icon)
Exemplo n.º 13
0
 def __init__(self, zm_monitor: Monitor):
     self.zm_monitor = zm_monitor
     self.grid = Grid((zm_monitor.dimensions()['height'],
                       zm_monitor.dimensions()['width']), 10, 10)
Exemplo n.º 14
0
class Game:
    """
    A class implementing main menu and graphics for 2048.
    Attributes
    ---------
    config: dict
        A JSON which contains configuration of the game (colors, sizes, coordinates etc.).
    best_score: int
        Best saved score obtained in 2048.
    grid_size: int
        Size of the game's grid.
    grid: Grid
        Class which implements logic of 2048.
    screen: pygame.surface.Surface:
        Instance of pygame's screen.
    fonts: Dict[str, pygame.font.Font]
        Fonts used by texts displayed during game_loop or
        while in main menu.
    buttons: Dict[str, Button]
        Dict of all required buttons for both game and
        main menu.
    """
    def __init__(self, config: dict) -> None:
        """
        Parameters
        ----------
        config: dict
            A JSON which contains configuration of the game (colors, sizes, coordinates etc.).
        """
        self.config: dict = config
        self.best_score: int = self.config["best_score"]
        self.grid_size: int = self.config['grid_size']
        self.grid: Grid = Grid()

        pygame.init()

        # pygame's attributes
        self.screen: pygame.surface.Surface = \
            pygame.display.set_mode((config['size'],
                                     config['size'] + self.config["header_height"]))

        self.fonts: Dict[str, pygame.font.Font] = {
            "text_font":
            pygame.font.SysFont(self.config['font'],
                                self.config['text_font_size'],
                                bold=True),
            "button_font":
            pygame.font.SysFont(self.config['font'],
                                self.config['button_font_size'],
                                bold=True),
            "title_font":
            pygame.font.SysFont(self.config['font'],
                                self.config['title_font_size'],
                                bold=True)
        }
        self.buttons: Dict[str, Button] = {
            "menu":
            Button(
                self.fonts["title_font"],
                ButtonColors(self.config["color"]["2048"],
                             self.config["color"]["2048"],
                             self.config["color"]["white"]),
                (10, 15, 150, 120)),
            "play":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config["color"]["play"],
                             self.config["color"]["64"],
                             self.config["color"]["black"]),
                (105, 400, 300, 45)),
            "monte_carlo":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config["color"]["play"],
                             self.config["color"]["64"],
                             self.config["color"]["black"]),
                (105, 500, 300, 45)),
            "reset":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config["color"]["play"],
                             self.config["color"]["64"],
                             self.config["color"]["black"]),
                (105, 250, 300, 45)),
            "current_score":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config['color']['score'],
                             self.config["color"]["64"],
                             self.config["color"]["white"]),
                (190, 15, 150, 60)),
            "best":
            Button(
                self.fonts["button_font"],
                ButtonColors(self.config['color']['score'],
                             self.config["color"]["64"],
                             self.config["color"]["white"]),
                (345, 15, 150, 60))
        }

        # initialize pygame
        pygame.display.set_caption('2048')
        icon: pygame.surface.Surface = pygame.transform.scale(
            pygame.image.load("images/game_icon.ico"), (32, 32))
        pygame.display.set_icon(icon)

    def check_game_status(self) -> None:
        """
        Check if game is won/lost. If it is true message is
        displayed and return to menu via button is enabled.
        """
        if self.grid.is_win() or self.grid.is_lose():
            size: int = self.config['size']
            screen = pygame.Surface(
                (size, size + self.config["header_height"]), pygame.SRCALPHA)
            screen.fill(self.config['color']['over'])
            self.screen.blit(screen, (0, 0))

            if self.grid.is_win():
                info: str = 'YOU WIN!'
                coords: Tuple[int, int] = (160, 180)
            else:
                info = 'GAME OVER!'
                coords = (140, 180)

            self.screen.blit(
                self.fonts["text_font"].render(info, True,
                                               self.config["color"]["dark"]),
                coords)
            while True:
                self.buttons["reset"].draw(self.screen, "Menu")
                pygame.display.update()

                for event in pygame.event.get():
                    pos: Tuple[int, int] = pygame.mouse.get_pos()
                    if self.buttons["reset"].handle_event(event, pos):
                        self.show_menu()

    def start_game(self) -> None:
        """
        Initialize Grid object and starts game loop.
        """
        self.grid = Grid()
        self.display()
        self.screen.blit(
            self.fonts["text_font"].render("NEW GAME!", True,
                                           self.config['color']['dark']),
            (140, 375))
        pygame.display.update()

        time.sleep(1)
        self.grid.generate_twos(number_of_twos=2)
        self.display()

    def display(self) -> None:
        """
        Generates objects during game loop.
        Created objects:
            - Score's banners.
            - Menu's button.
            - Game's grid.
        """
        self.screen.fill(self.config['color']['background'])
        box: int = self.config['size'] // 4
        padding = self.config['padding']

        self.buttons["menu"].draw(self.screen, "2048")
        self.buttons["current_score"].draw(self.screen,
                                           f"SCORE: {self.grid.score}")
        self.buttons["best"].draw(self.screen, f"BEST: {self.best_score}")

        for i in range(self.grid_size):
            for j in range(self.grid_size):
                color: Tuple[int, int, int] =\
                    self.config['color'][str(self.grid[i, j])]
                pygame.draw.rect(self.screen, color,
                                 (j * box + padding, i * box + padding +
                                  self.config["header_height"],
                                  box - 2 * padding, box - 2 * padding), 0)
                if self.grid[i, j] != 0:
                    if self.grid[i, j] in (2, 4):
                        text_color = self.config['color']['dark']
                    else:
                        text_color = self.config['color']['light']

                    self.screen.blit(
                        self.fonts["text_font"].render(f"{self.grid[i, j]:>4}",
                                                       True, text_color),
                        (j * box + 4 * padding,
                         i * box + 7 * padding + self.config["header_height"]))

            pygame.display.update()

    def update_grid(self, current_grid: np.ndarray) -> None:
        """
        If after move grid changed 2/4 is added to a grid, then screen is updated.
        At the end checks for ether win or lose.
        """
        if not np.array_equal(self.grid, current_grid):
            self.grid.generate_twos(number_of_twos=1)
            self.display()
            self.check_game_status()

    def bot_move(self, bot: MonteCarloTreeSearch,
                 all_moves: List[Callable[[], bool]]) -> None:
        """
        Performs a move returned by bot, then checks if grid was updated.

        Parameters
        ----------
        bot: MonteCarloTreeSearch
            Bot object which performs Monte Carlo Search to find best next move.
        all_moves: List[Callable[[], bool]]
            List containing all possible grid's move.
        """
        current_grid: np.ndarray = np.copy(self.grid.grid)
        all_moves[bot(asynchronous=True)]()
        self.update_grid(current_grid)

    def player_move(self, event: pygame.event.Event) -> None:
        """
        Performs move given by a player, then checks if grid was updated.

        Parameters
        ----------
        event: pygame.event.Event
            Event in which method checks if player performed grid's move.
        """
        if str(event.key) in self.config['keys']:
            key = self.config['keys'][str(event.key)]

            current_grid = np.copy(self.grid.grid)
            self.grid.move(key)
            self.best_score = max(self.best_score, self.grid.score)
            self.update_grid(current_grid)

    def game_loop(self, use_bot: bool) -> None:
        """
        Game loop in which either player or bot make
        moves until games is finished. After game is over by clicking
        menu button user can go back to main menu. Loop can be broken
        either by pressing q, exiting created game's window or pressing
        return button.

        Parameters
        ----------
        use_bot: bool
            Boolean which determines if player or bot is playing.
        """
        self.start_game()
        bot: MonteCarloTreeSearch = MonteCarloTreeSearch(self.grid)
        all_moves_list: List[Callable[[], bool]] = get_moves_list(self.grid)

        while True:
            if use_bot:
                self.bot_move(bot, all_moves_list)

            for event in pygame.event.get():
                pos: Tuple[int, int] = pygame.mouse.get_pos()
                if Game.check_for_quit(event):
                    break

                if not use_bot and event.type == pygame.KEYDOWN:
                    self.player_move(event)

                if self.buttons["menu"].handle_event(event, pos):
                    self.show_menu()

    def show_menu(self) -> None:
        """
        Generates main menu.
        Player or bot path can be chosen.
        """
        while True:
            self.screen.fill(self.config["color"]["background"])

            self.screen.blit(
                pygame.transform.scale(
                    pygame.image.load("images/game_icon.ico"), (300, 300)),
                (100, 50))

            self.buttons["play"].draw(self.screen, "Play")
            self.buttons["monte_carlo"].draw(self.screen, "Monte Carlo")
            pygame.display.update()

            for event in pygame.event.get():
                pos: Tuple[int, int] = pygame.mouse.get_pos()
                if Game.check_for_quit(event):
                    break

                if self.buttons["play"].handle_event(event, pos):
                    self.game_loop(use_bot=False)
                if self.buttons["monte_carlo"].handle_event(event, pos):
                    self.game_loop(use_bot=True)

    @staticmethod
    def check_for_quit(event: pygame.event.Event) -> bool:
        """
        Checks if game's window was closed or 'q' was pressed if yes game is shut down.

        Parameters
        ----------
        event: pygame.event.Event
            Pygame's event in which method checks if game should shut down.

        Returns
        -------
        bool
            True if player chose to quit.
        """
        if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_q:
            pygame.quit()
            return True

        return False
Exemplo n.º 15
0
                    if var_name in ds.variables:
                        if var_risico == 'H':
                            RH2 = 100*(ds.PSFC*ds.Q2/0.622)/(611.2*np.exp(17.67*(ds.T2-273.15)/((ds.T2-273.15)+243.5)))
                            values = RH2.values

                        elif var_risico == 'P':
                            values = ds[var_name].values - last_p
                            last_p = ds[var_name].values

                        else:
                            values = ds[var_name].values

                        lats = ds['XLAT'].values[0,:,:]
                        lons = ds['XLONG'].values[0,:,:]
                        min_lat, max_lat, min_lon, max_lon, n_rows, n_cols = lats[0,0], lats[-1,0], lons[0,0], lons[0,-1], lats.shape[0], lons.shape[1]
                        grid = Grid(lats, lons, regular=False)

                        out_date_str = date.strftime('%Y%m%d%H%M')

                        out_file = f'{output_dir}/{out_date_str}_wrf_{var_risico}.zbin'
                        write_gzip_binary(out_file, values, grid)

                        file_list.write(path.abspath(out_file) + '\n')
            except Exception as e: 
                print('exception', f)
                traceback.print_exc(e)
                
            
    # observations
    sub_dirs = sorted(list(filter(lambda d: not path.isfile(d), listdir(observations_dir))))
    nc_files = []
Exemplo n.º 16
0
                    x = x + 1
                elif pinarray[x, y - 1] != -1:
                    y = y + 1
            pinarray.itemset(x, y, pinno)
            # print(pinno," ", [data[1][0],x,y,data[1][3],data[1][4]])
            y_prev = data[1][2]
    pinArray.append(pinarray)
    # print(pinarray)
    return pinarray


if __name__ == '__main__':
    tracemalloc.start()

    IO = Input_Output()
    grids = Grid()

    config = IO.readInput()
    deriveComponents()

    for Comp in grids.getComponents():
        parts_min_distance = Comp.getPartsMinDist()
        parts_max_distance = Comp.getPartsMaxDist()
        net_points = [Comp.getNetPoints()]
        NoOfSquares = Comp.getNoOfParts()

        parts_size = Comp.getPartsSize()

        pinArray = []

        for eachPart in Comp.getParts():
Exemplo n.º 17
0
else:
    density = DensityModel(shape=tuple(args.grid))

# get the velocity model dimension
dimension = len(vel.shape())

if dimension == 2:
    nz, nx = tuple(args.grid)
    dz, dx = tuple(args.spacing)
else:
    nz, nx, ny = tuple(args.grid)
    dz, dx, dy = tuple(args.spacing)

compiler = Compiler(program_version=args.tool, c_code=args.ccode)

grid = Grid(shape=vel.shape())
grid.add_source()

# apply CFL conditions
dt = cfl.calc_dt(dimension=dimension,
                 space_order=2,
                 spacing=tuple(args.spacing),
                 vel_model=vel.model)
timesteps = cfl.calc_num_timesteps(args.time, dt)

params = {
    'compiler': compiler,
    'grid': grid,
    'vel_model': vel,
    'density': density,
    'timesteps': timesteps,
    actual_step = sim.add_iteration_step(step_name, copy_previous=True)
    actual_step['abaqus'].create_step_folder(abaqus_handler.get_path('output'))
    previous_step = sim.get_previous_iterations()

    # Read pore pressure from previous ended simulation stored in **_pore-pressure.csv and store those in actual step
    # as grid values. Those can be used to generate randomly lowered pore pressure values.
    pore_pressure_import = abaqus_handler.engine.read_csv_file(
        file=abaqus_handler.get_file(
            f'output_file_{previous_step["abaqus"].name}_pore-pressure'),
        x_coord_row=0,
        y_coord_row=1,
        z_coord_row=2,
        values_row={'pore_pressure': 3})

    # Initiate a new temporary grid for imported pore pressure
    pore_pressure_import_grid = Grid()
    pore_pressure_import_grid.initiate_grid(pore_pressure_import,
                                            'pore_pressure')

    # Transform pore pressure from imported grid to abaqus engine's grid
    transformer = GridTransformer()
    transformer.add_grid(actual_step['abaqus'].grid, 'abaqus')
    transformer.add_grid(pore_pressure_import_grid, 'import')
    transformer.find_nearest_neighbors('import', 'abaqus', 4)
    transformer.transition('import', 'pore_pressure', 'abaqus')

    # Read previously imported pore pressure dict from actual step into node_value_dict
    node_value_dict = actual_step['abaqus'].grid.get_node_values(
        'pore_pressure')

    # Randomize the imported pore pressure values
Exemplo n.º 19
0
from utils.grid import Grid
from utils.cells import Position, Cells
from dikjstra.forGrids import Dikjstra

# Map set up
gameMap = Grid(5, 10)

gameMap.cells[2][3] = Cells.wall.value
#gameMap.cells[3][4] = Cells.wall.value
gameMap.cells[4][3] = Cells.wall.value
gameMap.cells[3][2] = Cells.wall.value

gameMap.print()

# Dikjstra
dikjstra = Dikjstra()
start = Position(0, 0)
end = Position(3, 3)

path = dikjstra.shortestPath(gameMap, start, end)

i = 0
for cell in path.asList():
    gameMap.cells[cell.row][cell.col] = i
    i = i + 1

gameMap.print()

print("Path:", path)
Exemplo n.º 20
0
class MCTSTestCase(unittest.TestCase):
    """
    Case which tests if Monte Carlo Tree Search
    bot is working correctly.
    """
    def setUp(self) -> None:
        """
        Initialize required objects for all the tests.
        """
        self.grid: Grid = Grid()
        self.bot: MonteCarloTreeSearch = MonteCarloTreeSearch(self.grid)

    def test_move_list(self) -> None:
        """
        Tests if list of all the moves is created properly.
        """
        list_of_moves: List[Callable[[], bool]] = get_moves_list(self.grid)
        self.assertEqual(len(list_of_moves), self.grid.grid_size)

        self.grid.grid = np.array([[0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 4, 2],
                                   [2, 0, 0, 4]])
        list_of_moves[0]()
        self.assertTrue((self.grid.grid == [[2, 2, 4, 2], [0, 0, 0, 4],
                                            [0, 0, 0, 0], [0, 0, 0, 0]]).all())
        list_of_moves[1]()
        self.assertTrue((self.grid.grid == [[0, 0, 0, 0], [0, 0, 0, 0],
                                            [0, 0, 0, 2], [2, 2, 4, 4]]).all())
        list_of_moves[2]()
        self.assertTrue((self.grid.grid == [[0, 0, 0, 0], [0, 0, 0, 0],
                                            [2, 0, 0, 0], [4, 8, 0, 0]]).all())
        list_of_moves[3]()
        self.assertTrue((self.grid.grid == [[0, 0, 0, 0], [0, 0, 0, 0],
                                            [0, 0, 0, 2], [0, 0, 4, 8]]).all())

    def test_random_move(self) -> None:
        """
        Tests if move was performed after call
        of random_move function.
        """
        test_grid: np.ndarray = np.array([[0, 0, 0, 0], [0, 2, 2, 0],
                                          [0, 2, 2, 0], [0, 0, 0, 0]])
        self.grid.grid = np.copy(test_grid)
        make_random_move(get_moves_list(self.grid))

        self.assertFalse((test_grid == self.grid.grid).all())

    @unittest.skipIf(False, "Set to False if bot verification not needed.")
    def test_bot(self) -> None:
        """
        Tests if bot works as designed.
        """
        self.grid = Grid()
        self.bot.grid = self.grid
        search_move_list: List[Callable[[], bool]] = get_moves_list(self.grid)

        self.grid.generate_twos(number_of_twos=2)
        while not (self.grid.is_win() or self.grid.is_lose()):
            ind = self.bot()
            search_move_list[ind]()
            self.grid.generate_twos(number_of_twos=1)
            print(self.grid)

        self.assertTrue(self.grid.is_win())
        self.assertFalse(self.grid.is_lose())
Exemplo n.º 21
0
 def setUp(self) -> None:
     """
     Initialize required objects for all the tests.
     """
     self.grid: Grid = Grid()
     self.bot: MonteCarloTreeSearch = MonteCarloTreeSearch(self.grid)