Skip to content

Commit

Permalink
more ruff stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
Rexicon226 committed Mar 22, 2024
1 parent 64fc7d5 commit 919e307
Show file tree
Hide file tree
Showing 13 changed files with 33 additions and 80 deletions.
11 changes: 9 additions & 2 deletions .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,15 @@ jobs:
- uses: actions/setup-python@v2
- uses: chartboost/ruff-action@v1
with:
args: --check .
fix_args: --fix .
args: check .
fix:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v2
- uses: chartboost/ruff-action@v1
with:
args: format .
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: 'style fixes by ruff'
Expand Down
20 changes: 5 additions & 15 deletions CompositeEnvironment.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,18 @@ def forward(self, y_pred, y_true):


class Environment:
def __init__(
self, image: Image, noisy: Image, radius: int, center: None | tuple
) -> None:
def __init__(self, image: Image, noisy: Image, radius: int, center: None | tuple) -> None:
self.image = image.copy()
self.radius = radius
self.noisy_image = noisy.copy()
self.center = center

def generate(self) -> Image:
masked = get_visible_image(
self.image, self.radius, self.noisy_image, self.center
)
masked = get_visible_image(self.image, self.radius, self.noisy_image, self.center)
return masked


def create_circular_mask(
h: int, w: int, radius: int, center: None | tuple = None
) -> np.ndarray:
def create_circular_mask(h: int, w: int, radius: int, center: None | tuple = None) -> np.ndarray:
if center is None: # use the middle of the image
center = (w / 2, h / 2)

Expand All @@ -52,9 +46,7 @@ def create_circular_mask(
return mask


def get_visible_image(
image: Image, radius: int, noisy: Image, center: None | tuple
) -> Image:
def get_visible_image(image: Image, radius: int, noisy: Image, center: None | tuple) -> Image:
# Find the size of the image
image = np.abs(image)

Expand Down Expand Up @@ -112,9 +104,7 @@ def dNoiseVis(self, inputpic):
ax[1][1].set_title("De-Noised Image Histogram")

fig.suptitle(
"Image Size: 256 x 256\nNoise Level: {}%\nAccuracy: {:.2f}%".format(
noise_level, loss
),
"Image Size: 256 x 256\nNoise Level: {}%\nAccuracy: {:.2f}%".format(noise_level, loss),
fontsize=16,
y=0.9,
)
Expand Down
2 changes: 0 additions & 2 deletions DNoise/dnoise.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,6 @@ def create_synced_dictionary(folder_name):
except ValueError:
continue



if image_type == "clean.jpeg":
# Add the clean image to the dictionary
sync_dir_inner[name] = file
Expand Down
13 changes: 4 additions & 9 deletions DNoise/helper_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from pathlib import Path


def walk_through_dir(dir_path):
"""
Walks through dir_path returning its contents.
Expand All @@ -32,9 +33,7 @@ def walk_through_dir(dir_path):
name of each subdirectory
"""
for dirpath, dirnames, filenames in os.walk(dir_path):
print(
f"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'."
)
print(f"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.")


def plot_decision_boundary(model: torch.nn.Module, X: torch.Tensor, y: torch.Tensor):
Expand Down Expand Up @@ -74,9 +73,7 @@ def plot_decision_boundary(model: torch.nn.Module, X: torch.Tensor, y: torch.Ten


# Plot linear data or training and test and predictions (optional)
def plot_predictions(
train_data, train_labels, test_data, test_labels, predictions=None
):
def plot_predictions(train_data, train_labels, test_data, test_labels, predictions=None):
"""
Plots linear training data and test data and compares predictions.
"""
Expand Down Expand Up @@ -222,9 +219,7 @@ def pred_and_plot_image(
target_image_pred_label = torch.argmax(target_image_pred_probs, dim=1)

# 8. Plot the image alongside the prediction and prediction probability
plt.imshow(
target_image.squeeze().permute(1, 2, 0)
) # make sure it's the right size for matplotlib
plt.imshow(target_image.squeeze().permute(1, 2, 0)) # make sure it's the right size for matplotlib
if class_names:
title = f"Pred: {class_names[target_image_pred_label.cpu()]} | Prob: {target_image_pred_probs.max().cpu():.3f}"
else:
Expand Down
5 changes: 1 addition & 4 deletions Pathfinding/Environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ class ACTS(enum.Enum):
def circleUpdate(base, add, radius, coordinates: Tuple[int, int]):
for y, ny in enumerate(base):
for x, nx in enumerate(base):
distance = sqrt(
(coordinates[0] - x) * (coordinates[0] - x)
+ (coordinates[1] - y) * (coordinates[1] - y)
)
distance = sqrt((coordinates[0] - x) * (coordinates[0] - x) + (coordinates[1] - y) * (coordinates[1] - y))
if distance < radius:
base[y][x] = add[y][x]

Expand Down
11 changes: 4 additions & 7 deletions Pathfinding/astar.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,7 @@ def a_star(self):
neighbor = (x + dx, y + dy)

if (0 <= neighbor[0] < 256) and (0 <= neighbor[1] < 256):
if (
self.terrain[neighbor[0], neighbor[1]] == 0
and neighbor not in visited
):
if self.terrain[neighbor[0], neighbor[1]] == 0 and neighbor not in visited:
distance = self.heuristic(neighbor, self.end)
heapq.heappush(queue, (distance, neighbor))
self.path.append(neighbor)
Expand Down Expand Up @@ -84,9 +81,9 @@ def animate(self):
self.ax[0][0].set_title("De-Noised Image")

self.fig.suptitle(
"A* Pathfinding Example"
"\nImage Size: 256 x 256\n"
"Noise Level: {}%\nAccuracy: {:.2f}%".format(noise_level, loss),
"A* Pathfinding Example" "\nImage Size: 256 x 256\n" "Noise Level: {}%\nAccuracy: {:.2f}%".format(
noise_level, loss
),
fontsize=16,
)

Expand Down
15 changes: 2 additions & 13 deletions Terrain/blobcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,7 @@ def mark_island(array, visited, i, j):
neighbors = [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]
for x, y in neighbors:
# If the adjacent cell is land and has not been visited yet, it's part of the same island
if (
x >= 0
and x < len(array)
and y >= 0
and y < len(array[i])
and array[x][y] == 1
and not visited[x][y]
):
if x >= 0 and x < len(array) and y >= 0 and y < len(array[i]) and array[x][y] == 1 and not visited[x][y]:
mark_island(array, visited, x, y)


Expand All @@ -74,10 +67,6 @@ def mark_island(array, visited, i, j):
axes[1].imshow(noisepic)
axes[1].set_title("Noisy")

print(
"Clean pic islands: {}, Noisy pic islands: {}".format(
pic_islands, noisepic_islands
)
)
print("Clean pic islands: {}, Noisy pic islands: {}".format(pic_islands, noisepic_islands))

plt.show()
4 changes: 1 addition & 3 deletions Terrain/border.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ def bordercheck(pic: Union[list[list[int]], np.ndarray]):

for i in range(len(pic)):
pic[i] = [abs(ele) for ele in pic[i]]
borderpic = copy.deepcopy(
pic
) # create a deep copy so that stuff doesn't get messed up
borderpic = copy.deepcopy(pic) # create a deep copy so that stuff doesn't get messed up

for x in range(len(pic)):
for y in range(len(pic)):
Expand Down
9 changes: 2 additions & 7 deletions Terrain/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,7 @@ def from_file(cls, filename):
def thresholded(self):
"""Get the thresholded map"""
return np.array(
[
[1 if self.map[y][x] > self.threshold else 0 for x in range(self.width)]
for y in range(self.height)
]
[[1 if self.map[y][x] > self.threshold else 0 for x in range(self.width)] for y in range(self.height)]
)

@property
Expand Down Expand Up @@ -72,9 +69,7 @@ def __neg__(self):

def build(self, octaves):
"""build the map"""
self.map = terraingen.terrain(
self.width, self.height, octaves, seed=random.randint(0, 1000000)
)
self.map = terraingen.terrain(self.width, self.height, octaves, seed=random.randint(0, 1000000))

def __mul__(self, other):
"""Multiply the map by a given value"""
Expand Down
7 changes: 1 addition & 6 deletions Terrain/pathcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,7 @@ def isPath(arr):
seed = random.randint(1, x * y * 1000)
if failedSeeds.count(seed) == 0 and setseed == 0:
solved = isPath(terraingen.terrain(x, y, octaves, seed=seed))
sys.stdout.write(
"\rChecking seed: "
+ str(seed)
+ ", Number: "
+ str(len(failedSeeds) + 1)
)
sys.stdout.write("\rChecking seed: " + str(seed) + ", Number: " + str(len(failedSeeds) + 1))
sys.stdout.flush()
if solved:
print("\nWorking Seed: " + str(seed))
Expand Down
6 changes: 1 addition & 5 deletions Terrain/sumPerlin.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@ def noiseMaps(
map2 = PerlinNoise(octaves1, seed + seedDifference)
discrete1 = [[map1([i / x, j / y]) for j in range(y)] for i in range(x)]
discrete2 = [
[
(difference * map2([i / x, j / y])) + (1 - difference) * (discrete1[i][j])
for j in range(y)
]
for i in range(x)
[(difference * map2([i / x, j / y])) + (1 - difference) * (discrete1[i][j]) for j in range(y)] for i in range(x)
]

return discrete1, discrete2
Expand Down
9 changes: 2 additions & 7 deletions Terrain/terraingen.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,10 @@ def terrain(x: int, y: int, octaves: int, progress: bool = False, seed: int = 0)

noise = PerlinNoise(octaves=octaves, seed=seed)
if progress:
picarr = [
[int(np.floor(noise([i / x, j / y]))) for j in range(y)]
for i in tqdm(range(x))
]
picarr = [[int(np.floor(noise([i / x, j / y]))) for j in range(y)] for i in tqdm(range(x))]
return picarr
if not progress:
picarr = [
[int(np.floor(noise([i / x, j / y]))) for j in range(y)] for i in range(x)
]
picarr = [[int(np.floor(noise([i / x, j / y]))) for j in range(y)] for i in range(x)]
return picarr


Expand Down
1 change: 1 addition & 0 deletions Terrain/timers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from math import floor, log10


class BaseTimer:
"""class for timing things such as testing performance
Expand Down

0 comments on commit 919e307

Please sign in to comment.