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

Use multiple gradients on a single ingredient #270

Merged
merged 7 commits into from
Jul 8, 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
9 changes: 6 additions & 3 deletions cellpack/autopack/Analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -828,9 +828,12 @@ def update_distance_distribution_dictionaries(

get_angles = False
if ingr.packing_mode == "gradient" and self.env.use_gradient:
self.center = center = self.env.gradients[ingr.gradient].mode_settings.get(
"center", center
)
if not isinstance(ingr.gradient, list):
self.center = center = self.env.gradients[
ingr.gradient
].mode_settings.get("center", center)
else:
self.center = center
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: maybe simply reverse if and else statements for readability?

Suggested change
if not isinstance(ingr.gradient, list):
self.center = center = self.env.gradients[
ingr.gradient
].mode_settings.get("center", center)
else:
self.center = center
if isinstance(ingr.gradient, list):
self.center = center
else:
self.center = self.env.gradients[
ingr.gradient
].mode_settings.get("center", center)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Thanks Ruge! This reminded me of another edge case of a single gradient in a list so I added that in as well here.

get_angles = True

# get angles wrt gradient
Expand Down
19 changes: 18 additions & 1 deletion cellpack/autopack/Environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -1700,7 +1700,24 @@ def getPointToDrop(
# get the most probable point using the gradient
# use the gradient weighted map and get mot probabl point
self.log.info("pick point from gradients %d", (len(allIngrPts)))
ptInd = self.gradients[ingr.gradient].pickPoint(allIngrPts)
if isinstance(ingr.gradient, list) and len(ingr.gradient) > 1:
if not hasattr(ingr, "combined_weight"):
gradient_list = [
gradient
for gradient_name, gradient in self.gradients.items()
if gradient_name in ingr.gradient
]
combined_weight = Gradient.get_combined_gradient_weight(
Copy link
Member

Choose a reason for hiding this comment

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

can you push the logic above into a generic Gradient.pick_point_from_weight that figures out wether it needs to combine weights and returns the ptInd

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Good call! I added a static method Gradient.pick_point_for_ingredient here

gradient_list
)
ingr.combined_weight = combined_weight

ptInd = Gradient.pick_point_from_weight(
ingr.combined_weight, allIngrPts
)

else:
ptInd = self.gradients[ingr.gradient].pickPoint(allIngrPts)
else:
# pick a point randomly among free points
# random or uniform?
Expand Down
75 changes: 64 additions & 11 deletions cellpack/autopack/Gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,67 @@ def __init__(self, gradient_data):

self.function = self.defaultFunction # lambda ?

@staticmethod
def scale_between_0_and_1(values):
"""
Scale values between 0 and 1
"""
max_value = numpy.nanmax(values)
min_value = numpy.nanmin(values)
return (values - min_value) / (max_value - min_value)

@staticmethod
def get_combined_gradient_weight(gradient_list):
"""
Combine the gradient weights

Parameters
----------
gradient_list: list
list of gradient objects

Returns
----------
numpy.ndarray
the combined gradient weight
"""
weight_list = numpy.zeros((len(gradient_list), len(gradient_list[0].weight)))
for i in range(len(gradient_list)):
weight_list[i] = Gradient.scale_between_0_and_1(gradient_list[i].weight)

combined_weight = numpy.mean(weight_list, axis=0)
combined_weight = Gradient.scale_between_0_and_1(combined_weight)

return combined_weight

@staticmethod
def pick_point_from_weight(weight, points):
"""
Picks a point from a list of points according to the given weight

Parameters
----------
weight: numpy.ndarray
the weight of each point

points: numpy.ndarray
list of grid point indices

Returns
----------
int
the index of the picked point
"""
weights_to_use = numpy.take(weight, points)
weights_to_use = Gradient.scale_between_0_and_1(weights_to_use)
weights_to_use[numpy.isnan(weights_to_use)] = 0

point_probabilities = weights_to_use / numpy.sum(weights_to_use)

point = numpy.random.choice(points, p=point_probabilities)

return point

def get_center(self):
"""get the center of the gradient grid"""
center = [0.0, 0.0, 0.0]
Expand All @@ -113,14 +174,6 @@ def normalize_vector(self, vector):
"""
return vector / numpy.linalg.norm(vector)

def get_normalized_values(self, values):
"""
Scale values between 0 and 1
"""
max_value = numpy.nanmax(values)
min_value = numpy.nanmin(values)
return (values - min_value) / (max_value - min_value)

def pickPoint(self, listPts):
"""
pick next random point according to the chosen function
Expand Down Expand Up @@ -205,7 +258,7 @@ def build_axis_weight_map(self, bb, master_grid_positions):

def set_weights_by_mode(self):

self.scaled_distances = self.get_normalized_values(self.distances)
self.scaled_distances = Gradient.scale_between_0_and_1(self.distances)

if (numpy.nanmax(self.scaled_distances) > 1.0) or (
numpy.nanmin(self.scaled_distances) < 0.0
Expand All @@ -232,7 +285,7 @@ def set_weights_by_mode(self):
-self.scaled_distances / self.weight_mode_settings["decay_length"]
)
# normalize the weight
self.weight = self.get_normalized_values(self.weight)
self.weight = Gradient.scale_between_0_and_1(self.weight)

if (numpy.nanmax(self.weight) > 1.0) or (numpy.nanmin(self.weight) < 0.0):
raise ValueError(
Expand Down Expand Up @@ -377,7 +430,7 @@ def create_voxelization(self, image_writer):
)
if channel_values is None:
continue
normalized_values = self.get_normalized_values(channel_values)
normalized_values = Gradient.scale_between_0_and_1(channel_values)
reshaped_values = numpy.reshape(
normalized_values, image_writer.image_size, order="F"
)
Expand Down
9 changes: 9 additions & 0 deletions cellpack/tests/packing-configs/test_grid_plot_config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "show_grid_plot",
"out": "cellpack/tests/outputs/",
"load_from_grid_file": false,
"overwrite_place_method": true,
"place_method": "spheresSST",
"save_analyze_result": true,
"show_grid_plot": true
}
18 changes: 0 additions & 18 deletions cellpack/tests/packing-configs/test_mesh_config.json

This file was deleted.

107 changes: 107 additions & 0 deletions cellpack/tests/recipes/v2/test_combined_gradient.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
{
"version": "1.0.0",
"format_version": "2.0",
"name": "test_combined_gradient",
"bounding_box": [
[
0,
0,
0
],
[
1000,
1000,
1
]
],
"gradients": {
"X_gradient": {
"description": "X gradient",
"mode": "X",
"pick_mode": "rnd",
"weight_mode": "exponential",
"weight_mode_settings": {
"decay_length": 0.3
}
},
"Y_gradient": {
"description": "Y gradient",
"mode": "Y",
"pick_mode": "rnd",
"weight_mode": "exponential",
"weight_mode_settings": {
"decay_length": 0.3
}
}
},
"objects": {
"base": {
"jitter_attempts": 10,
"orient_bias_range": [
-3.1415927,
3.1415927
],
"rotation_range": 6.2831,
"cutoff_boundary": 0,
"max_jitter": [
1,
1,
0
],
"perturb_axis_amplitude": 0.1,
"packing_mode": "random",
"principal_vector": [
0,
0,
1
],
"rejection_threshold": 50,
"place_method": "spheresSST",
"cutoff_surface": 42,
"rotation_axis": [
0,
0,
1
],
"available_regions": {
"interior": {},
"surface": {},
"outer_leaflet": {},
"inner_leaflet": {}
}
},
"sphere_25": {
"type": "single_sphere",
"inherit": "base",
"color": [
0.5,
0.5,
0.5
],
"radius": 25,
"max_jitter": [
1,
1,
0
],
"packing_mode": "gradient",
"gradient": [
"X_gradient",
"Y_gradient"
]
}
},
"composition": {
"space": {
"regions": {
"interior": [
"A"
]
}
},
"A": {
"object": "sphere_25",
"count": 500
}
}
}
Loading