Skip to content

Commit

Permalink
fix: log compatability with bots
Browse files Browse the repository at this point in the history
  • Loading branch information
eladyaniv01 committed Sep 23, 2020
1 parent ff8d6db commit 8960716
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 45 deletions.
27 changes: 11 additions & 16 deletions MapAnalyzer/Debugger.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from typing import Any, Dict, Optional, Tuple, TYPE_CHECKING, Union

import numpy as np
import sc2
from loguru import logger
from numpy import ndarray
from sc2 import BotAI
Expand Down Expand Up @@ -35,7 +34,10 @@ def __init__(self, level: str = "ERROR") -> None:

def __call__(self, record: Dict[str, Any]) -> bool:
levelno = logger.level(self.level).no
return record["level"].no >= levelno
if 'sc2.' not in record["name"].lower():
return record["level"].no >= levelno
return False



class MapAnalyzerDebugger:
Expand All @@ -45,20 +47,13 @@ class MapAnalyzerDebugger:

def __init__(self, map_data: "MapData", loglevel: str = "ERROR") -> None:
self.map_data = map_data
if not self.map_data.arcade:
self.logger = sc2.main.logger
else:
self.logger = logger
self.warnings = warnings
self.warnings.filterwarnings('ignore', category=DeprecationWarning)
self.warnings.filterwarnings('ignore', category=RuntimeWarning)

self.logger.remove()
self.local_log_filter = LocalLogFilter(module_name=LOG_MODULE, level=loglevel)
self.log_filter = LogFilter(level=loglevel)
self.log_format = LOG_FORMAT
self.logger.add(sys.stderr, format=self.log_format, filter=self.local_log_filter)
self.logger.add(sys.stderr, format=self.log_format, filter=self.log_filter)
self.log_filter = LogFilter(level=loglevel)
logger.add(sys.stderr, format=self.log_format, filter=self.log_filter)

@staticmethod
def scatter(*args, **kwargs):
Expand All @@ -79,13 +74,13 @@ def save(self, filename: str) -> bool:

for i in inspect.stack():
if 'test_suite.py' in str(i):
self.logger.info(f"Skipping save operation on test runs")
self.logger.debug(f"index = {inspect.stack().index(i)} {i}")
logger.info(f"Skipping save operation on test runs")
logger.debug(f"index = {inspect.stack().index(i)} {i}")
return True
import matplotlib.pyplot as plt
full_path = os.path.join(os.path.abspath("."), f"{filename}")
plt.savefig(f"{filename}.png")
self.logger.debug(f"Plot Saved to {full_path}")
logger.debug(f"Plot Saved to {full_path}")

def plot_regions(self,
fontdict: Dict[str, Union[str, int]]) -> None:
Expand Down Expand Up @@ -223,11 +218,11 @@ def plot_influenced_path(self, start: Union[Tuple[int, int], Point2],
ax: plt.Axes = plt.subplot(1, 1, 1)
if path is not None:
path = np.flipud(path) # for plot align
self.map_data.logger.info("Found")
logger.info("Found")
x, y = zip(*path)
ax.scatter(x, y, s=3, c='green')
else:
self.map_data.logger.info("Not Found")
logger.info("Not Found")

x, y = zip(*[start, goal])
ax.scatter(x, y)
Expand Down
29 changes: 13 additions & 16 deletions MapAnalyzer/MapData.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,23 @@
from typing import Dict, List, Optional, Set, Tuple, Union

import numpy as np
from loguru import logger
from numpy import float64, int64, ndarray
from pkg_resources import DistributionNotFound, get_distribution
from sc2.bot_ai import BotAI
from sc2.position import Point2
from scipy.ndimage import binary_fill_holes, center_of_mass, generate_binary_structure, label as ndlabel
from scipy.spatial import distance


from MapAnalyzer.Debugger import MapAnalyzerDebugger
from MapAnalyzer.Pather import MapAnalyzerPather
from MapAnalyzer.Region import Region
from MapAnalyzer.utils import get_sets_with_mutual_elements
from .constants import BINARY_STRUCTURE, MAX_REGION_AREA, MIN_REGION_AREA, CORNER_MIN_DISTANCE
from .constructs import ChokeArea, MDRamp, VisionBlockerArea, PathLibChoke
from .constants import BINARY_STRUCTURE, CORNER_MIN_DISTANCE, MAX_REGION_AREA, MIN_REGION_AREA
from .constructs import ChokeArea, MDRamp, PathLibChoke, VisionBlockerArea
from .decorators import progress_wrapped
from .exceptions import CustomDeprecationWarning

from pkg_resources import get_distribution, DistributionNotFound


try:
__version__ = get_distribution('sc2mapanalyzer')
except DistributionNotFound:
Expand Down Expand Up @@ -71,7 +69,6 @@ def __init__(self, bot: BotAI, loglevel: str = "ERROR", arcade: bool = False,
# plugins
self.log_level = loglevel
self.debugger = MapAnalyzerDebugger(self, loglevel=self.log_level)
self.logger = self.debugger.logger
self.pather = MapAnalyzerPather(self)
self.connectivity_graph = None # set by pather
self.pathlib_map = self.pather.pathlib_map
Expand All @@ -82,10 +79,10 @@ def __init__(self, bot: BotAI, loglevel: str = "ERROR", arcade: bool = False,
if not self.arcade:
self.base_locations: list = bot.expansion_locations_list
else:
self.logger.info(f" {__version__} Starting in Arcade mode")
logger.info(f" {__version__} Starting in Arcade mode")
self.base_locations: list = []

self.logger.info(f"{__version__} Compiling {self.map_name} " + WHITE)
logger.info(f"{__version__} Compiling {self.map_name} " + WHITE)
self._compile_map()

"""Properties"""
Expand Down Expand Up @@ -151,7 +148,7 @@ def get_pyastar_grid(self,
"""
if air_pathing is not None:
self.logger.warning(CustomDeprecationWarning(oldarg='air_pathing', newarg='self.get_clean_air_grid()'))
logger.warning(CustomDeprecationWarning(oldarg='air_pathing', newarg='self.get_clean_air_grid()'))
return self.pather.get_pyastar_grid(default_weight=default_weight,
include_destructables=include_destructables,
)
Expand Down Expand Up @@ -310,13 +307,13 @@ def add_cost(self, position: Tuple[int, int], radius: int, grid: ndarray, weight

"""Utility methods"""

def log(self, msg):
def log(msg):
"""
Lazy logging
"""
self.logger.debug(f"{msg}")
logger.debug(f"{msg}")

def save(self, filename):
"""
Expand Down Expand Up @@ -455,7 +452,7 @@ def closest_towards_point(
if isinstance(points, list):
return points[self.closest_node_idx(node=target, nodes=points)]
else:
self.logger.warning(type(points))
logger.warning(type(points))
return points[self.closest_node_idx(node=target, nodes=points)]

"""Query methods"""
Expand Down Expand Up @@ -731,7 +728,7 @@ def _calc_chokes(self) -> None:
new_choke.areas.append(area)
self.map_chokes.append(new_choke)
else: # pragma: no cover
self.logger.debug(f" [{self.map_name}] Cant add {choke} with 0 points")
logger.debug(f" [{self.map_name}] Cant add {choke} with 0 points")

def _calc_regions(self) -> None:
# compute Region
Expand Down Expand Up @@ -801,7 +798,7 @@ def plot_map(
"""
if save is not None:
self.logger.warning(CustomDeprecationWarning(oldarg='save', newarg='self.save()'))
logger.warning(CustomDeprecationWarning(oldarg='save', newarg='self.save()'))
self.debugger.plot_map(fontdict=fontdict, figsize=figsize)

def plot_influenced_path(self,
Expand All @@ -817,7 +814,7 @@ def plot_influenced_path(self,
"""
if plot is not None:
self.logger.warning(CustomDeprecationWarning(oldarg='plot', newarg='self.show()'))
logger.warning(CustomDeprecationWarning(oldarg='plot', newarg='self.show()'))

self.debugger.plot_influenced_path(start=start,
goal=goal,
Expand Down
17 changes: 9 additions & 8 deletions MapAnalyzer/Pather.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

import numpy as np
import pyastar.astar_wrapper as pyastar
from loguru import logger
from numpy import ndarray
from sc2.position import Point2
from sc2.ids.unit_typeid import UnitTypeId as UnitID
from sc2.position import Point2
from skimage import draw as skdraw

from MapAnalyzer.constants import NONPATHABLE_RADIUS_FACTOR, RESOURCE_BLOCKER_RADIUS_FACTOR, GEYSER_RADIUS_FACTOR
from MapAnalyzer.constants import GEYSER_RADIUS_FACTOR, NONPATHABLE_RADIUS_FACTOR, RESOURCE_BLOCKER_RADIUS_FACTOR
from MapAnalyzer.exceptions import OutOfBoundsException, PatherNoPointsException
from MapAnalyzer.Region import Region
from .sc2pathlibp import Sc2Map
Expand Down Expand Up @@ -94,7 +95,7 @@ def find_lowest_cost_points(self, from_pos: Point2, radius: int, grid: np.ndarra
ri, ci = skdraw.disk(center=(int(from_pos[0]), int(from_pos[1])), radius=radius, shape=grid.shape)
if len(ri) == 0 or len(ci) == 0:
# this happens when the center point is near map edge, and the radius added goes beyond the edge
self.map_data.logger.debug(OutOfBoundsException(from_pos))
logger.debug(OutOfBoundsException(from_pos))
# self.map_data.logger.trace()
return None
points = self.map_data.indices_to_points((ri, ci))
Expand Down Expand Up @@ -150,10 +151,10 @@ def pathfind(self, start: Tuple[int, int], goal: Tuple[int, int], grid: Optional
start = int(start[0]), int(start[1])
goal = int(goal[0]), int(goal[1])
else:
self.map_data.logger.warning(PatherNoPointsException(start=start, goal=goal))
logger.warning(PatherNoPointsException(start=start, goal=goal))
return None
if grid is None:
self.map_data.logger.warning("Using the default pyastar grid as no grid was provided.")
logger.warning("Using the default pyastar grid as no grid was provided.")
grid = self.get_pyastar_grid()

path = self.pyastar.astar_path(grid, start=start, goal=goal, allow_diagonal=allow_diagonal)
Expand All @@ -176,15 +177,15 @@ def pathfind(self, start: Tuple[int, int], goal: Tuple[int, int], grid: Optional
legal_path.pop(0)
return legal_path
else:
self.map_data.logger.debug(f"No Path found s{start}, g{goal}")
logger.debug(f"No Path found s{start}, g{goal}")
return None

def add_cost(self, position: Tuple[int, int], radius: int, arr: ndarray, weight: int = 100,
safe: bool = True, initial_default_weights: int = 0) -> ndarray:
ri, ci = skdraw.disk(center=(int(position[0]), int(position[1])), radius=radius, shape=arr.shape)
if len(ri) == 0 or len(ci) == 0:
# this happens when the center point is near map edge, and the radius added goes beyond the edge
self.map_data.logger.debug(OutOfBoundsException(position))
logger.debug(OutOfBoundsException(position))
# self.map_data.logger.trace()
return arr

Expand All @@ -209,7 +210,7 @@ def in_bounds_ri(y):

arr[ri, ci] += weight
if np.any(arr < 1) and safe:
self.map_data.logger.warning(
logger.warning(
"You are attempting to set weights that are below 1. falling back to the minimum (1)")
arr = np.where(arr < 1, 1, arr)
return arr
9 changes: 4 additions & 5 deletions tests/test_suite.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

from _pytest.python import Metafunc
from hypothesis import given, settings
from loguru import logger
from sc2.position import Point2

from MapAnalyzer.MapData import MapData
from MapAnalyzer.utils import get_map_file_list, mock_map_data
from tests.mocksetup import get_map_datas, logger, random, st

logger = logger
from tests.mocksetup import get_map_datas, random, st


# From https://docs.pytest.org/en/latest/example/parametrize.html#a-quick-port-of-testscenarios
Expand Down Expand Up @@ -107,7 +106,7 @@ def test_chokes(self, map_data: MapData) -> None:
for choke in map_data.map_chokes:
for p in choke.points:
assert (choke in map_data.where_all(p)), \
map_data.logger.error(f"<Map : {map_data}, Choke : {choke},"
logger.error(f"<Map : {map_data}, Choke : {choke},"
f" where : {map_data.where(choke.center)} point : {choke.center}>")

def test_vision_blockers(self, map_data: MapData) -> None:
Expand All @@ -116,5 +115,5 @@ def test_vision_blockers(self, map_data: MapData) -> None:
assert (vb in all_chokes)
for p in vb.points:
assert (vb in map_data.where_all(p)), \
map_data.logger.error(f"<Map : {map_data}, Choke : {vb},"
logger.error(f"<Map : {map_data}, Choke : {vb},"
f" where_all : {map_data.where_all(vb.center)} point : {vb.center}>")

0 comments on commit 8960716

Please sign in to comment.