class WriterTensorboardX():
    def __init__(self, log_dir, logger, enable):
        self.writer = None
        if enable:
            log_dir = str(log_dir)
            try:
                self.writer = importlib.import_module(
                    'tensorboardX').SummaryWriter(log_dir)
            except ImportError:
                message = "Warning: TensorboardX visualization is configured to use, but currently not installed on " \
                    "this machine. Please install the package by 'pip install tensorboardx' command or turn " \
                    "off the option in the 'config.json' file."
                logger.warning(message)
        self.step = 0
        self.mode = ''

        self.tb_writer_ftns = [
            'add_scalar', 'add_scalars', 'add_image', 'add_images',
            'add_audio', 'add_text', 'add_histogram', 'add_pr_curve',
            'add_embedding'
        ]
        self.tag_mode_exceptions = ['add_histogram', 'add_embedding']
        self.timer = Timer()

    def set_step(self, step, mode='train'):
        self.mode = mode
        self.step = step
        if step == 0:
            self.timer.reset()
        else:
            duration = self.timer.check()
            self.add_scalar('steps_per_sec', 1 / duration)

    def __getattr__(self, name):
        """
        If visualization is configured to use:
            return add_data() methods of tensorboard with additional information (step, tag) added.
        Otherwise:
            return a blank function handle that does nothing
        """
        if name in self.tb_writer_ftns:
            add_data = getattr(self.writer, name, None)

            def wrapper(tag, data, *args, **kwargs):
                if add_data is not None:
                    # add mode(train/valid) tag
                    if name not in self.tag_mode_exceptions:
                        tag = '{}/{}'.format(tag, self.mode)
                    add_data(tag, data, self.step, *args, **kwargs)

            return wrapper
        else:
            # default action for returning methods defined in this class, set_step() for instance.
            try:
                attr = object.__getattr__(name)
            except AttributeError:
                raise AttributeError(
                    "type object 'WriterTensorboardX' has no attribute '{}'".
                    format(name))
            return attr
Ejemplo n.º 2
0
class TensorboardWriter:
    def __init__(self, log_dir, logger, enabled):
        if enabled:
            log_dir = str(log_dir)

            # Setup tensorboard writer
            try:
                from torch.utils import tensorboard
            except ImportError:
                message = (
                    'Warning: Tensorboard is configured to use, but currently '
                    'not installed. Please upgrade PyTorch to version >= 1.1 '
                    'for using `torch.utils.tensorboard` or turn off the option '
                    'in the `config.json` file.'
                )
                logger.warning(message)
            else:
                self._writer = tensorboard.SummaryWriter(log_dir)

        self._step = 0
        self._mode = ''

        self._tag_mode_exceptions = {'add_histogram', 'add_embedding'}
            
        self._timer = Timer()

    def set_step(self, step, mode='train'):
        self._step = step
        self._mode = mode

        if step == 0:
            self._timer.reset()
        else:
            duration = self._timer.check()
            self.add_scalar('steps_per_sec', 1 / duration)

    def __getattr__(self, name):
        """
        If tensorboard is configured to use, return methods of tensorboard
        with additional information (mode, step) added.
        Otherwise, return a blank function.
        """
        add_data = getattr(self._writer, name, None)

        def wrapper(tag, data, *args, **kwargs):
            if add_data is not None:
                if name not in self._tag_mode_exceptions:
                    tag = '{}/{}'.format(tag, self._mode)
                add_data(tag, data, self._step, *args, **kwargs)
        
        return wrapper
Ejemplo n.º 3
0
class PlayerAnimationSystem(Applicator):
    def __init__(self, name):
        super(PlayerAnimationSystem, self).__init__()
        self.componenttypes = PlayerData, Frames, MotionType, Facing, Sprite

        self.frame_timer = Timer(60, True)

        self.sprite_sheet = SpriteSheet(name)

        self.motion_type = "standing"
        self.facing = "down"
        self.last_facing = self.facing
        self.last_motion_type = self.motion_type

        self.surface = None
        self.sprite_surface = None

    def process(self, world, componentsets):
        for playerdata, frames, motion_type, facing, sprite in componentsets:

            if not playerdata.life:
                return

            self.frame_timer.update()

            self.facing = facing.get()
            self.motion_type = motion_type.get()

            if (self.facing != self.last_facing) or (self.motion_type != self.last_motion_type):
                frames.set(0)

            if frames.get() == self.sprite_sheet.get_sprite_sheet_width(self.motion_type) / 128:
                frames.set(0)

            self.last_facing = self.facing
            self.last_motion_type = self.motion_type

            self.surface = self.sprite_sheet.get_surface(frames.get(), motion_type.get(), facing.get())
            self.sprite_surface = sprite.surface

            rect = SDL_Rect(0, 0)
            SDL_FillRect(self.sprite_surface, None, 0x000000)
            SDL_BlitSurface(self.surface, None, self.sprite_surface, rect)

            if self.frame_timer.check():
                self.frame_timer.reset()
                self.frame_timer.activate()
                frames.bump()
class TensorboardWriter():
    def __init__(self, log_dir, logger, enabled):
        self.writer = None
        self.selected_module = ""

        if enabled:
            log_dir = str(log_dir)

            # Retrieve vizualization writer.
            succeeded = False
            for module in ["torch.utils.tensorboard", "tensorboardX"]:
                try:
                    self.writer = importlib.import_module(
                        module).SummaryWriter(log_dir)
                    succeeded = True
                    break
                except ImportError:
                    succeeded = False
                self.selected_module = module

            if not succeeded:
                message = "Warning: visualization (Tensorboard) is configured to use, but currently not installed on " \
                    "this machine. Please install either TensorboardX with 'pip install tensorboardx', upgrade " \
                    "PyTorch to version >= 1.1 for using 'torch.utils.tensorboard' or turn off the option in " \
                    "the 'config.json' file."
                logger.warning(message)

        self.step = 0
        self.mode = ''

        self.tb_writer_ftns = {
            'add_scalar', 'add_scalars', 'add_image', 'add_images',
            'add_audio', 'add_text', 'add_histogram', 'add_pr_curve',
            'add_embedding'
        }
        self.tag_mode_exceptions = {'add_histogram', 'add_embedding'}

        self.timer = Timer()

    def set_step(self, step, mode='train'):
        self.mode = mode
        self.step = step
        if step == 0:
            self.timer.reset()
        else:
            duration = self.timer.check()
            self.add_scalar('steps_per_sec', 1 / duration)

    def __getattr__(self, name):
        """
        If visualization is configured to use:
            return add_data() methods of tensorboard with additional information (step, tag) added.
        Otherwise:
            return a blank function handle that does nothing
        """
        if name in self.tb_writer_ftns:
            add_data = getattr(self.writer, name, None)

            def wrapper(tag, data, *args, **kwargs):
                if add_data is not None:
                    # add mode(train/valid) tag
                    if name not in self.tag_mode_exceptions:
                        tag = '{}/{}'.format(tag, self.mode)
                    add_data(tag, data, self.step, *args, **kwargs)

            return wrapper
        else:
            # default action for returning methods defined in this class, set_step() for instance.
            try:
                attr = object.__getattr__(name)
            except AttributeError:
                raise AttributeError(
                    "type object '{}' has no attribute '{}'".format(
                        self.selected_module, name))
            return attr
Ejemplo n.º 5
0
class NPC:
    def __init__(self, renderer, factory, json_data):

        self.dialog_timer = Timer(10000)
        self.close_dialog_timer = Timer(10000)

        self.db = DataBase()

        self.renderer = renderer
        self.factory = factory

        data = json.loads(json_data)

        self.name = data["name"]
        self.start_pos = data["start_pos"]

        self.npc_data = self.db.get_npc(self.name)

        self.level = self.npc_data["level"]
        self.quest = self.npc_data["quest"]
        self.sprite_size = 128
        self.position = [0, 0]
        self.movement = [0, 0]

        self.moving = False

        self.npc_sprites = [
            RESOURCES.get_path("{0}_standing.png".format(self.name)),
            RESOURCES.get_path("{0}_walking.png".format(self.name))
        ]

        self.sprite_sheets = {}
        self.sprites = []

        self.facing = Facing.LEFT_DOWN
        self.last_facing = self.facing

        self.motion_type = MotionType.STANDING
        self.last_motion_type = self.motion_type

        self.frame_index = 0
        self.walk_frames = 60
        self.move_rate = 100

        self.init_sprite_sheet()

        self.dialogs = self.db.get_npc_dialog(self.name)
        self.dialog_box = None
        self.dialog_sprites = []
        self.text = None

    def init_sprite_sheet(self):
        for motion_type in range(MotionType.COUNT):
            self.load_image(self.npc_sprites[motion_type], motion_type)

    def load_image(self, file_path, motion_type):
        sprite_sheets = self.sprite_sheets.get(file_path)
        if not sprite_sheets:
            sprite_surface = self.factory.from_image(file_path)
            self.sprite_sheets[motion_type] = sprite_surface

    def update(self, position, elapsed_time):

        self.position = position
        self.sprites.clear()
        self.frame_index += 1

        if self.frame_index == (self.sprite_sheets[self.motion_type].size[0] / self.sprite_size):
            self.frame_index = 0

        if not self.moving:
            move = dice(self.move_rate)
            if move[0] == self.move_rate - 1:
                self.moving = True
                self.walk_frames = 60
                facing = dice(Facing.COUNT - 1)
                self.facing = facing[0]

        if self.moving:
            if self.walk_frames:
                self.motion_type = MotionType.WALKING

                if self.facing == 0:
                    self.movement[0] -= 2
                    self.movement[1] += 1
                    self.facing = Facing.LEFT_DOWN
                elif self.facing == 1:
                    self.movement[1] += 1
                    self.facing = Facing.DOWN
                elif self.facing == 2:
                    self.movement[0] += 2
                    self.movement[1] += 1
                    self.facing = Facing.RIGHT_DOWN
                elif self.facing == 3:
                    self.movement[0] += 2
                    self.facing = Facing.RIGHT
                elif self.facing == 4:
                    self.movement[0] += 2
                    self.movement[1] -= 1
                    self.facing = Facing.RIGHT_UP
                elif self.facing == 5:
                    self.movement[1] -= 1
                    self.facing = Facing.UP
                elif self.facing == 6:
                    self.movement[0] -= 2
                    self.movement[1] -= 1
                    self.facing = Facing.LEFT_UP
                elif self.facing == 7:
                    self.movement[0] -= 2
                    self.facing = Facing.LEFT

                self.walk_frames -= 1
            else:
                self.moving = False
                self.motion_type = MotionType.STANDING

        x = int((int(self.start_pos[0]) + self.position[0] + self.movement[0]) - (self.sprite_size / 2))
        y = int((int(self.start_pos[1]) + self.position[1] + self.movement[1]) - (self.sprite_size / 2))

        self.position = x, y

        sprite_sheet = self.sprite_sheets[self.motion_type]

        sprite_crop = [self.frame_index * self.sprite_size,
                       self.facing * self.sprite_size,
                       self.sprite_size,
                       self.sprite_size]

        sprite = sprite_sheet.subsprite(sprite_crop)
        sprite.position = self.position

        self.sprites.append(sprite)

        """
        renderer = self.renderer

        src_rect = SDL_Rect()

        src_rect.x = frame_index * sprite_size
        src_rect.y = facing * sprite_size
        src_rect.w = sprite_size
        src_rect.h = sprite_size

        dest_rect = SDL_Rect()

        dest_rect.x = x
        dest_rect.y = y
        dest_rect.w = sprite_size
        dest_rect.h = sprite_size

        SDL_RenderCopy(renderer, sprite.texture, src_rect, dest_rect)
        """

    def get_sprites(self):
        return self.sprites

    def dialog_update(self):

        self.dialog_timer.update()
        self.close_dialog_timer.update()

        if self.dialog_timer.check():
            self.dialog_timer.reset()
            self.close_dialog_timer.activate()

            self.create_dialog()

        if self.close_dialog_timer.check():
            self.close_dialog_timer.reset()
            self.dialog_timer.activate()
            self.dialog_box = None
            self.dialog_sprites.clear()

    def create_dialog(self):

        self.text = dice(len(self.dialogs) - 1)

        name = self.dialogs[self.text[0]]['npc']
        text = self.dialogs[self.text[0]]['text']
        message = {0: "{0}:".format(name)}

        max_chars = 24
        i = 1
        for j in range(0, len(text), max_chars):
            message[i] = text[j:j + max_chars]
            i += 1

        self.dialog_box = DialogBox(self.factory,
                                    font_size=32,
                                    fg_color=Colors.WHITE,
                                    bg_color=Colors.BLACK,
                                    font_name="04B_20__.TTF",
                                    text=message,
                                    position=self.position,
                                    renderer=self.renderer)

        sprites = self.dialog_box.get_sprites()
        for sprite in sprites:
            self.dialog_sprites.append(sprite)
Ejemplo n.º 6
0
class CometWriter:
    def __init__(self,
                 logger,
                 project_name: Optional[str] = None,
                 experiment_name: Optional[str] = None,
                 api_key: Optional[str] = None,
                 log_dir: Optional[str] = None,
                 offline: bool = False,
                 **kwargs):
        if not _COMET_AVAILABLE:
            raise ImportError(
                "You want to use `comet_ml` logger which is not installed yet,"
                " install it with `pip install comet-ml`.")

        self.project_name = project_name
        self.experiment_name = experiment_name
        self.kwargs = kwargs

        self.timer = Timer()

        if (api_key is not None) and (log_dir is not None):
            self.mode = "offline" if offline else "online"
            self.api_key = api_key
            self.log_dir = log_dir

        elif api_key is not None:
            self.mode = "online"
            self.api_key = api_key
            self.log_dir = None
        elif log_dir is not None:
            self.mode = "offline"
            self.log_dir = log_dir
        else:
            logger.warning(
                "CometLogger requires either api_key or save_dir during initialization."
            )

        if self.mode == "online":
            self.experiment = CometExperiment(
                api_key=self.api_key,
                project_name=self.project_name,
                **self.kwargs,
            )
        else:
            self.experiment = CometOfflineExperiment(
                offline_directory=self.log_dir,
                project_name=self.project_name,
                **self.kwargs,
            )

        if self.experiment_name:
            self.experiment.set_name(self.experiment_name)

    def set_step(self, step, epoch=None, mode='train') -> None:
        self.mode = mode
        self.step = step
        self.epoch = epoch
        if step == 0:
            self.timer.reset()
        else:
            duration = self.timer.check()
            self.add_scalar({'steps_per_sec': 1 / duration})

    def log_hyperparams(self, params: Dict[str, Any]) -> None:
        self.experiment.log_parameters(params)

    def log_code(self, file_name=None, folder='models/') -> None:
        self.experiment.log_code(file_name=file_name, folder=folder)

    def add_scalar(self,
                   metrics: Dict[str, Union[torch.Tensor, float]],
                   step: Optional[int] = None,
                   epoch: Optional[int] = None) -> None:
        metrics_renamed = {}
        for key, val in metrics.items():
            tag = '{}/{}'.format(key, self.mode)
            if is_tensor(val):
                metrics_renamed[tag] = val.cpu().detach()
            else:
                metrics_renamed[tag] = val
        if epoch is None:
            self.experiment.log_metrics(metrics_renamed,
                                        step=self.step,
                                        epoch=self.epoch)
        else:
            self.experiment.log_metrics(metrics_renamed, epoch=epoch)

    def add_plot(self, figure_name, figure):
        """
        Primarily for log gate plots
        """
        self.experiment.log_figure(figure_name=figure_name, figure=figure)

    def add_hist3d(self, hist, name):
        """
        Primarily for log gate plots
        """
        self.experiment.log_histogram_3d(hist, name=name)

    def reset_experiment(self):
        self.experiment = None

    def finalize(self) -> None:
        self.experiment.end()
        self.reset_experiment()
Ejemplo n.º 7
0
class NPC:
    def __init__(self, window, data):

        self.dialog_timer = Timer(10000, activated=True)
        self.close_dialog_timer = Timer(10000)

        self.db = DataBase()

        self.window = window
        self.renderer = window.renderer

        self.name = data["name"]
        self.level = data["level"]
        self.quest = data["quest"]
        self.sprite_size = 128
        self.position = [0, 0]
        self.movement = [0, 0]

        self.moving = False

        self.npc_sprites = [
            RESOURCES.get_path("{0}_standing.png".format(self.name)),
            RESOURCES.get_path("{0}_walking.png".format(self.name))
        ]

        self.factory = sdl2.ext.SpriteFactory(sdl2.ext.TEXTURE,
                                              renderer=self.renderer)

        self.sprite_sheets = {}

        self.facing = Facing.LEFT_DOWN
        self.last_facing = self.facing

        self.motion_type = MotionType.STANDING
        self.last_motion_type = self.motion_type

        self.frame_index = 0
        self.walk_frames = 60

        self.init_sprite_sheet()

        self.dialogs = self.db.get_npc_dialog(self.name)
        self.dialog_box = None
        self.msg = None

    def init_sprite_sheet(self):
        for motion_type in range(MotionType.COUNT):
            self.load_image(self.npc_sprites[motion_type], motion_type)

    def load_image(self, file_path, motion_type):
        sprite_sheets = self.sprite_sheets.get(file_path)
        if not sprite_sheets:
            sprite_surface = self.factory.from_image(file_path)
            self.sprite_sheets[motion_type] = sprite_surface

    def update(self, position, elapsed_time):

        self.position = position

        self.frame_index += 1

        if self.frame_index == (self.sprite_sheets[self.motion_type].size[0] /
                                self.sprite_size):
            self.frame_index = 0

        if not self.moving:
            move = dice(200)
            if move[0] == 200:
                self.moving = True
                self.walk_frames = 60
                facing = dice(Facing.COUNT - 1)
                self.facing = facing[0]

        if self.moving:
            if self.walk_frames:
                self.motion_type = MotionType.WALKING

                if self.facing == 0:
                    # print("LEFT_DOWN")
                    self.movement[0] -= 2
                    self.movement[1] += 1
                    self.facing = Facing.LEFT_DOWN
                elif self.facing == 1:
                    # print("DOWN")
                    self.movement[1] += 1
                    self.facing = Facing.DOWN
                elif self.facing == 2:
                    # print("RIGHT_DOWN")
                    self.movement[0] += 2
                    self.movement[1] += 1
                    self.facing = Facing.RIGHT_DOWN
                elif self.facing == 3:
                    # print("RIGHT")
                    self.movement[0] += 2
                    self.facing = Facing.RIGHT
                elif self.facing == 4:
                    # print("RIGHT_UP")
                    self.movement[0] += 2
                    self.movement[1] -= 1
                    self.facing = Facing.RIGHT_UP
                elif self.facing == 5:
                    # print("UP")
                    self.movement[1] -= 1
                    self.facing = Facing.UP
                elif self.facing == 6:
                    # print("LEFT_UP")
                    self.movement[0] -= 2
                    self.movement[1] -= 1
                    self.facing = Facing.LEFT_UP
                elif self.facing == 7:
                    # print("LEFT")
                    self.movement[0] -= 2
                    self.facing = Facing.LEFT

                self.walk_frames -= 1
            else:
                self.moving = False
                self.motion_type = MotionType.STANDING

        self.dialog_update()

    def draw(self):

        renderer = self.renderer.renderer
        motion_type = self.motion_type
        facing = self.facing
        frame_index = self.frame_index
        position = self.position
        movement = self.movement

        sprite = self.sprite_sheets[motion_type]
        sprite_size = self.sprite_size

        x = int(((WindowSize.WIDTH / 2) + position[0] + movement[0]) -
                (sprite_size / 2))
        y = int(((WindowSize.HEIGHT / 2) + position[1] + movement[1]) -
                (sprite_size / 2))

        src_rect = SDL_Rect()

        src_rect.x = frame_index * sprite_size
        src_rect.y = facing * sprite_size
        src_rect.w = sprite_size
        src_rect.h = sprite_size

        dest_rect = SDL_Rect()

        dest_rect.x = x
        dest_rect.y = y
        dest_rect.w = sprite_size
        dest_rect.h = sprite_size

        render.SDL_RenderCopy(renderer, sprite.texture, src_rect, dest_rect)

        self.dialog_draw((x, y))

    def dialog_update(self):

        self.dialog_timer.update()

        if self.dialog_timer.check():
            self.dialog_timer.reset()
            self.close_dialog_timer.activate()
            self.msg = dice(len(self.dialogs) - 1)
            self.dialog_box = Dialog(self.window, Colors.WHITHE, 16, (10, 400),
                                     Colors.BLACK)

        self.close_dialog_timer.update()

        if self.close_dialog_timer.check():
            self.close_dialog_timer.reset()
            self.dialog_timer.activate()
            self.dialog_box = None

    def dialog_draw(self, position):

        if self.dialog_box:

            x, y = position

            name = self.dialogs[self.msg[0]]['npc']
            text = self.dialogs[self.msg[0]]['text']
            message = {0: "{0}:".format(name)}

            max_chars = 24
            i = 1
            for j in range(0, len(text), max_chars):
                message[i] = text[j:j + max_chars]
                i += 1

            self.dialog_box.draw(message, (x, y - 100))