Skip to content

Commit

Permalink
Merge pull request #84 from bhosale2/update-0.2.3
Browse files Browse the repository at this point in the history
Blacken example files (#83)
  • Loading branch information
armantekinalp authored May 16, 2022
2 parents 86e1d33 + be9bdc4 commit 074769a
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 54 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
black:
@black --version
@black --required-version 21.12b0 elastica tests
@black --required-version 21.12b0 elastica tests examples


black_check:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
# FIXME without appending sys.path make it more generic
sys.path.append("../../../../")
from elastica import *
from elastica.experimental.connection_contact_joint.parallel_connection import get_connection_vector_straight_straight_rod, SurfaceJointSideBySide
from elastica.experimental.connection_contact_joint.parallel_connection import (
get_connection_vector_straight_straight_rod,
SurfaceJointSideBySide,
)
from elastica._calculus import difference_kernel
from examples.JointCases.joint_cases_postprocessing import (
plot_position,
Expand Down Expand Up @@ -82,34 +85,54 @@ class ParallelConnection(

# Apply a contraction force on rod one.
class ContractionForce(NoForces):
def __init__(self, ramp, force_mag, ):
def __init__(
self,
ramp,
force_mag,
):
self.ramp = ramp
self.force_mag = force_mag

def apply_forces(self, system, time: np.float64 = 0.0):
# Ramp the force
factor = min(1.0, time / self.ramp)

system.external_forces[:] -= factor * difference_kernel(self.force_mag * system.tangents)
system.external_forces[:] -= factor * difference_kernel(
self.force_mag * system.tangents
)


parallel_connection_sim.add_forcing_to(rod_one).using(ContractionForce, ramp=0.5, force_mag=1. )
parallel_connection_sim.add_forcing_to(rod_one).using(
ContractionForce, ramp=0.5, force_mag=1.0
)

# Connect rod 1 and rod 2
(
rod_one_direction_vec_in_material_frame,
rod_two_direction_vec_in_material_frame,
offset_btw_rods,
) = get_connection_vector_straight_straight_rod(rod_one, rod_two, (0, n_elem), (0, n_elem))
) = get_connection_vector_straight_straight_rod(
rod_one, rod_two, (0, n_elem), (0, n_elem)
)

for i in range(n_elem):
parallel_connection_sim.connect(
first_rod=rod_one, second_rod=rod_two, first_connect_idx=i, second_connect_idx=i
).using(
SurfaceJointSideBySide, k=1E2, nu=1E-5, k_repulsive = 1E3, rod_one_direction_vec_in_material_frame=rod_one_direction_vec_in_material_frame[:,i],
rod_two_direction_vec_in_material_frame = rod_two_direction_vec_in_material_frame[:,i],
offset_btw_rods = offset_btw_rods[i]
SurfaceJointSideBySide,
k=1e2,
nu=1e-5,
k_repulsive=1e3,
rod_one_direction_vec_in_material_frame=rod_one_direction_vec_in_material_frame[
:, i
],
rod_two_direction_vec_in_material_frame=rod_two_direction_vec_in_material_frame[
:, i
],
offset_btw_rods=offset_btw_rods[i],
) # k=kg/s2 nu=kg/s 1e-2


class ParallelConnecitonCallback(CallBackBaseClass):
"""
Call back function for parallel connection
Expand Down
13 changes: 7 additions & 6 deletions examples/MuscularSnake/muscle_forces.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def __init__(
side_of_body,
muscle_start_end_index,
step,
post_processing,
post_processing,
):
"""
Expand Down Expand Up @@ -76,7 +76,7 @@ def __init__(

self.post_processing = post_processing
self.step = step
self.counter=0
self.counter = 0

def apply_forces(self, system, time: np.float = 0.0):
forces = self._apply_forces(
Expand All @@ -90,15 +90,16 @@ def apply_forces(self, system, time: np.float = 0.0):
system.external_forces,
)

if self.counter % self.step ==0:
if self.counter % self.step == 0:
self.post_processing["time"].append(time)
self.post_processing["step"].append(self.counter)
self.post_processing["external_forces"].append(forces.copy())
self.post_processing["element_position"].append(np.cumsum(system.lengths).copy())
self.post_processing["element_position"].append(
np.cumsum(system.lengths).copy()
)

self.counter += 1


@staticmethod
@njit(cache=True)
def _apply_forces(
Expand Down Expand Up @@ -130,4 +131,4 @@ def _apply_forces(
] += difference_kernel(muscle_forces)

external_forces += forces
return forces
return forces
4 changes: 2 additions & 2 deletions examples/MuscularSnake/muscular_snake.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,8 @@ class MuscularSnakeSimulator(
) = get_connection_vector_straight_straight_rod(
rod_one,
rod_two,
(muscle_start_connection_index[idx],muscle_end_connection_index[idx]),
(0, rod_two.n_elems)
(muscle_start_connection_index[idx], muscle_end_connection_index[idx]),
(0, rod_two.n_elems),
)
straight_straight_rod_connection_list.append(
[
Expand Down
41 changes: 21 additions & 20 deletions examples/MuscularSnake/post_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@


def plot_video_with_surface(
rods_history: Sequence[Dict],
video_name="video.mp4",
fps=60,
step=1,
vis2D=True,
**kwargs,
rods_history: Sequence[Dict],
video_name="video.mp4",
fps=60,
step=1,
vis2D=True,
**kwargs,
):
plt.rcParams.update({"font.size": 22})

folder_name = kwargs.get("folder_name","")
folder_name = kwargs.get("folder_name", "")

# 2d case <always 2d case for now>
import matplotlib.animation as animation
Expand Down Expand Up @@ -115,7 +115,7 @@ def plot_video_with_surface(
ax.add_artist(sphere_artists[sphere_idx])

# ax.set_aspect("equal")
video_name_3D = folder_name+"3D_" + video_name
video_name_3D = folder_name + "3D_" + video_name

with writer.saving(fig, video_name_3D, dpi):
with plt.style.context("seaborn-whitegrid"):
Expand All @@ -127,7 +127,7 @@ def plot_video_with_surface(
)
if not inst_position.shape[1] == inst_radius.shape[0]:
inst_position = 0.5 * (
inst_position[..., 1:] + inst_position[..., :-1]
inst_position[..., 1:] + inst_position[..., :-1]
)

rod_scatters[rod_idx]._offsets3d = (
Expand Down Expand Up @@ -206,7 +206,7 @@ def plot_video_with_surface(
ax.add_artist(sphere_artists[sphere_idx])

ax.set_aspect("equal")
video_name_2D = folder_name+"2D_xy_" + video_name
video_name_2D = folder_name + "2D_xy_" + video_name

with writer.saving(fig, video_name_2D, dpi):
with plt.style.context("seaborn-whitegrid"):
Expand All @@ -218,7 +218,7 @@ def plot_video_with_surface(
)
if not inst_position.shape[1] == inst_radius.shape[0]:
inst_position = 0.5 * (
inst_position[..., 1:] + inst_position[..., :-1]
inst_position[..., 1:] + inst_position[..., :-1]
)

rod_lines[rod_idx].set_xdata(inst_position[0])
Expand Down Expand Up @@ -297,7 +297,7 @@ def plot_video_with_surface(
ax.add_artist(sphere_artists[sphere_idx])

ax.set_aspect("equal")
video_name_2D = folder_name+"2D_zy_" + video_name
video_name_2D = folder_name + "2D_zy_" + video_name

with writer.saving(fig, video_name_2D, dpi):
with plt.style.context("seaborn-whitegrid"):
Expand All @@ -309,7 +309,7 @@ def plot_video_with_surface(
)
if not inst_position.shape[1] == inst_radius.shape[0]:
inst_position = 0.5 * (
inst_position[..., 1:] + inst_position[..., :-1]
inst_position[..., 1:] + inst_position[..., :-1]
)

rod_lines[rod_idx].set_xdata(inst_position[2])
Expand Down Expand Up @@ -390,7 +390,7 @@ def plot_video_with_surface(
ax.add_artist(sphere_artists[sphere_idx])

ax.set_aspect("equal")
video_name_2D = folder_name+"2D_xz_" + video_name
video_name_2D = folder_name + "2D_xz_" + video_name

with writer.saving(fig, video_name_2D, dpi):
with plt.style.context("seaborn-whitegrid"):
Expand All @@ -402,7 +402,7 @@ def plot_video_with_surface(
)
if not inst_position.shape[1] == inst_radius.shape[0]:
inst_position = 0.5 * (
inst_position[..., 1:] + inst_position[..., :-1]
inst_position[..., 1:] + inst_position[..., :-1]
)

rod_lines[rod_idx].set_xdata(inst_position[0])
Expand Down Expand Up @@ -437,10 +437,11 @@ def plot_video_with_surface(
# See https://github.com/matplotlib/matplotlib/issues/8560/
plt.close(plt.gcf())


def plot_snake_velocity(
plot_params: dict,
period,
filename="slithering_snake_velocity.png",
plot_params: dict,
period,
filename="slithering_snake_velocity.png",
):
time_per_period = np.array(plot_params["time"]) / period
avg_velocity = np.array(plot_params["avg_velocity"])
Expand Down Expand Up @@ -469,6 +470,7 @@ def plot_snake_velocity(
fig.legend(prop={"size": 20})
fig.savefig(filename)


def compute_projected_velocity(plot_params: dict, period):

time_per_period = np.array(plot_params["time"]) / period
Expand All @@ -494,7 +496,7 @@ def compute_projected_velocity(plot_params: dict, period):
center_of_mass[(i + 1) * period_step : (i + 2) * period_step]
- center_of_mass[(i + 0) * period_step : (i + 1) * period_step],
axis=0,
)
)

# Average the rod directions over multiple periods and get the direction of the rod.
direction_of_rod = np.mean(center_of_mass_averaged_over_one_period, axis=0)
Expand Down Expand Up @@ -526,4 +528,3 @@ def compute_projected_velocity(plot_params: dict, period):
average_velocity_over_simulation[0],
average_velocity_over_simulation[1],
)

13 changes: 10 additions & 3 deletions examples/RestartExample/restart_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
"""

import sys

sys.path.append("../../")
from elastica import *


class RestartExampleSimulator(BaseSystemCollection, Constraints, Forcing, CallBacks):
pass

Expand Down Expand Up @@ -62,7 +64,7 @@ class RestartExampleSimulator(BaseSystemCollection, Constraints, Forcing, CallBa

# After finalize you can load restart file. This step is important for current implementation of restart functions,
# it is required to load restart files after the finalize step.
LOAD_FROM_RESTART = False
LOAD_FROM_RESTART = False
SAVE_DATA_RESTART = True
restart_file_location = "data/"

Expand All @@ -76,11 +78,16 @@ class RestartExampleSimulator(BaseSystemCollection, Constraints, Forcing, CallBa
dt = 0.01 * dl
total_steps = int(final_time / dt)

time = integrate(timestepper, restart_example_simulator, final_time, total_steps, restart_time=restart_time)
time = integrate(
timestepper,
restart_example_simulator,
final_time,
total_steps,
restart_time=restart_time,
)

# Save all the systems appended on the simulator class. Since in this example have only one system, under the
# `restart_file_location` directory there is one file called system_0.npz . For each system appended on the simulator
# separate system_#.npz file will be created.
if SAVE_DATA_RESTART:
save_state(restart_example_simulator, restart_file_location, time, True)

Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ class InclinedRodRodContact(
shear_modulus = E / (poisson_ratio + 1.0)

# Rod orientations
start = np.zeros(3,)
start = np.zeros(
3,
)
inclination = np.deg2rad(30)
direction = np.array([0.0, np.cos(inclination), np.sin(inclination)])
normal = np.array([0.0, -np.sin(inclination), np.cos(inclination)])
Expand All @@ -56,7 +58,7 @@ class InclinedRodRodContact(
nu,
E,
poisson_ratio,
shear_modulus = shear_modulus,
shear_modulus=shear_modulus,
)

rod_one.velocity_collection[:] += 0.05 * -normal.reshape(3, 1)
Expand Down Expand Up @@ -94,9 +96,7 @@ class InclinedRodRodContact(

# Add call backs
class RodCallBack(CallBackBaseClass):
"""
"""
""" """

def __init__(self, step_skip: int, callback_params: dict):
CallBackBaseClass.__init__(self)
Expand Down Expand Up @@ -130,15 +130,19 @@ def make_callback(self, system, time, current_step: int):
) # list which collected data will be append
# set the diagnostics for rod and collect data
inclined_rod_rod_contact_sim.collect_diagnostics(rod_one).using(
RodCallBack, step_skip=step_skip, callback_params=post_processing_dict_rod1,
RodCallBack,
step_skip=step_skip,
callback_params=post_processing_dict_rod1,
)

post_processing_dict_rod2 = defaultdict(
list
) # list which collected data will be append
# set the diagnostics for rod and collect data
inclined_rod_rod_contact_sim.collect_diagnostics(rod_two).using(
RodCallBack, step_skip=step_skip, callback_params=post_processing_dict_rod2,
RodCallBack,
step_skip=step_skip,
callback_params=post_processing_dict_rod2,
)

inclined_rod_rod_contact_sim.finalize()
Expand Down
Loading

0 comments on commit 074769a

Please sign in to comment.