Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add time limit to measurements #7

Merged
merged 3 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@

# The spelling list filename.
spelling_word_list_filename=['spelling/spelling_wordlist.txt']

# Change tab title
release = '1.0.0'
html_title = f"{project} {release} Documentation"
4 changes: 4 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@

#####################
sIArena Documentation
#####################

.. include:: /rst/titlepage.rst


Expand Down
4 changes: 2 additions & 2 deletions docs/rst/titlepage.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

##############################
******************************
IArena Searching Documentation
##############################
******************************

**IArena** is an **open source** project that aims to provide a **simple** and **easy to use** framework for playing games in a manual or **automatic** way.
It is developed with educational and research purposes related with **computer science** and **artificial intelligence**.
Expand Down
3 changes: 2 additions & 1 deletion docs/spelling/spelling_wordlist.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
IArena
Colab
IArena
sIArena
26 changes: 23 additions & 3 deletions src/sIArena/measurements/measurements.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import math
import threading
import time
from typing import List, Tuple

from sIArena.terrain.Terrain import Coordinate, Terrain, Path
Expand All @@ -25,7 +27,9 @@ def measure_function(
- The average time that the function has elapsed to find it
"""

# A paused timer to measure time
# Function to return the result as a parameter
def func_wrapper(func, terrain, result):
result.append(func(terrain))

best_path_cost = math.inf
best_path = None
Expand All @@ -36,11 +40,27 @@ def measure_function(
if debug:
print(f"Running iteration {i}...")

# TODO add max time stop
# List for the result of the function
result = []

# Thread with timeout
thread = threading.Thread(target=func_wrapper, args=(search_function, terrain, result,))

# Start timer
timer = Timer()
path = search_function(terrain)

# Start thread
thread.start()
thread.join(timeout=max_seconds)

# Store time
times.append(timer.elapsed_s())

if thread.is_alive():
raise TimeoutError(f"Function {search_function.__name__} took more than {max_seconds} seconds to finish.")
else:
path = result[0]

if not terrain.is_full_path(path):
raise ValueError(f"Found Incorrect path with function {search_function.__name__}: {path}")

Expand Down
17 changes: 16 additions & 1 deletion src/sIArena/terrain/plot/plot_2D.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
def plot_terrain_2D(
terrain: Terrain,
paths: List[Path] = [],
paths_legends: List[str] = None,
use_cost_as_path_legend: bool = False,
colors: List[str] = ['r', 'y', 'm', 'k', 'c', 'g', 'b'],
cmap: str = 'terrain',
title: str = 'Terrain',
Expand All @@ -20,17 +22,30 @@ def plot_terrain_2D(
plt.plot(terrain.origin[1], terrain.origin[0], 'r+')
plt.plot(terrain.destination[1], terrain.destination[0], 'rx')

# Set path legends if unset
paths_legends_ = paths_legends
if paths_legends_ is None:
paths_legends_ = [""]
while len(paths_legends_) < len(paths):
paths_legends_.append("")

# Plot the paths
for i, p in enumerate(paths):
if use_cost_as_path_legend:
paths_legends_[i] = f'{paths_legends_[i]} ({terrain.get_path_cost(p)})'
plt.plot(
[pos[1] for pos in p],
[pos[0] for pos in p],
colors[i % len(colors)])
colors[i % len(colors)],
label=paths_legends_[i],)

plt.xlabel('row')
plt.ylabel('col')
plt.title(title)

if paths_legends or use_cost_as_path_legend:
plt.legend()

plt.colorbar()
plt.show(block=False)
plt.pause(0.001)
2 changes: 1 addition & 1 deletion src/sIArena/terrain/plot/plot_3D.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,5 @@ def plot_terrain_3D(
ax.set_xlabel('row')
ax.set_ylabel('col')

fig.title(title)
fig.suptitle(title)
plt.show()
20 changes: 20 additions & 0 deletions src/sIArena/utils/threading_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import threading

def run_function_with_timeout(func, timeout):

# Function to return the result as a parameter
def func_wrapper(result):
result.append(func())

# List for the result of the function
result = []

# Thread with timeout
thread = threading.Thread(target=func_wrapper, args=(result,))
thread.start()
thread.join(timeout)

if thread.is_alive():
return None
else:
return result[0]
Loading