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

Position sampling in Environments with holes. #100

Merged
merged 3 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
39 changes: 26 additions & 13 deletions ratinabox/Environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ def plot_environment(self,

return fig, ax

def sample_positions(self, n=10, method="uniform_jitter"):
def sample_positions(self, n=10, method="uniform_jitter",force_method=False):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we reference this param in the doc string

"""Scatters 'n' locations across the environment which can act as, for example, the centres of gaussian place fields, or as a random starting position.
If method == "uniform" an evenly spaced grid of locations is returned. If method == "uniform_jitter" these locations are jittered slightly (i.e. random but span the space). Note; if n doesn't uniformly divide the size (i.e. n is not a square number in a square environment) then the largest number that can be scattered uniformly are found, the remaining are randomly placed.
Args:
Expand Down Expand Up @@ -581,33 +581,46 @@ def sample_positions(self, n=10, method="uniform_jitter"):
positions[:, 1] = np.random.uniform(
self.extent[2], self.extent[3], size=n
)
if (self.is_rectangular is False) or (self.has_holes is True):
# in this case, the positions you have sampled within the extent of the environment may not actually fall within it's legal area (i.e. they could be outside the polygon boundary or inside a hole). Brute force this by randomly resampling these points until all fall within the env.
for i, pos in enumerate(positions):
if self.check_if_position_is_in_environment(pos) == False:
pos = self.sample_positions(n=1, method="random").reshape(
-1
) # this recursive call must pass eventually, assuming the env is sufficiently large. this is why we don't need a while loop
positions[i] = pos
elif method[:7] == "uniform":
ex = self.extent
area = (ex[1] - ex[0]) * (ex[3] - ex[2])
if (self.has_holes is True):
area -= sum(polygon_area(hole) for hole in self.holes)
delta = np.sqrt(area / n)
x = np.linspace(ex[0] + delta /2, ex[1] - delta /2, int((ex[1] - ex[0])/delta))
y = np.linspace(ex[2] + delta /2, ex[3] - delta /2, int((ex[3] - ex[2])/delta))
positions = np.array(np.meshgrid(x, y)).reshape(2, -1).T

if (self.is_rectangular is False) or (self.has_holes is True):
# in this case, the positions you have sampled within the extent of the environment may not actually fall within it's legal area (i.e. they could be outside the polygon boundary or inside a hole).
delpos = [i for (i,pos) in enumerate(positions) if self.check_if_position_is_in_environment(pos) == False]
positions = np.delete(positions,delpos,axis=0) # this will delete illegal positions

n_uniformly_distributed = positions.shape[0]
if method[7:] == "_jitter":
positions += np.random.uniform(
-0.45 * delta, 0.45 * delta, positions.shape
)
)
n_remaining = n - n_uniformly_distributed
if n_remaining > 0:
positions_remaining = self.sample_positions(
n=n_remaining, method="random"
)
if force_method:
# resample from available positions (repeating sampled positions)
positions_remaining = [positions[i] for i in np.random.choice(range(len(positions)),n_remaining, replace=False)]
else:
# or brute force this by randomly resampling these points until all fall within the env.
positions_remaining = self.sample_positions(
n=n_remaining, method="random"
)
positions = np.vstack((positions, positions_remaining))

if (self.is_rectangular is False) or (self.has_holes is True):
# in this case, the positions you have sampled within the extent of the environment may not actually fall within it's legal area (i.e. they could be outside the polygon boundary or inside a hole). Brute force this by randomly resampling these points until all fall within the env.
for i, pos in enumerate(positions):
if self.check_if_position_is_in_environment(pos) == False:
pos = self.sample_positions(n=1, method="random").reshape(
-1
) # this recursive call must pass eventually, assuming the env is sufficiently large. this is why we don't need a while loop
positions[i] = pos
return positions

def discretise_environment(self, dx=None):
Expand Down
9 changes: 9 additions & 0 deletions ratinabox/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@
"""OTHER USEFUL FUNCTIONS"""
"""Geometry functions"""

def polygon_area(hole):
"""Given 4-point list defining a hole in the environment, returns its area.
Args:
hole (array): list of list of points defining the hole.
Returns:
scalar: area of the hole.
"""
x, y = zip(*hole)
return round(0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))),2)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where does this formula come from? Also is it limited to holes with four points? By the way we already list shapely as a requirement so we could use shapely.Polygon.area for this...just a thought

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's interesting I've never heard of this formula before. Could you (a) either refer to it as the shoelace formula in the doc string or (b) use shapely.geometry.Polygon(hole).area instead.

Also, clarify that isn't just 4-corner holes that works, its any sized holes. Finally, in the docstrng make sure you remember to clarify the intended shape of holes ((N, 2) for N >= 3 presumably). Thanks!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, excellent! I did not realize shapely was imported. This is the same formula that shapely uses: the formula to calculate the area of a polygon given the list of points considering connectedness across the list of points. So we do not this in utils.py.


def get_perpendicular(a=None):
"""Given 2-vector, a, returns its perpendicular
Expand Down