nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py
jacobian_inverse
(link_lengths, joint_angles)
return np.linalg.pinv(J)
140
149
def jacobian_inverse(link_lengths, joint_angles): J = np.zeros((2, N_LINKS)) for i in range(N_LINKS): J[0, i] = 0 J[1, i] = 0 for j in range(i, N_LINKS): J[0, i] -= link_lengths[j] * np.sin(np.sum(joint_angles[:j])) J[1, i] += link_lengths[j] * np.cos(np.sum(joint_angles[:j])) return np.linalg.pinv(J)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py#L140-L149
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
93.82716
10
3
100
0
def jacobian_inverse(link_lengths, joint_angles): J = np.zeros((2, N_LINKS)) for i in range(N_LINKS): J[0, i] = 0 J[1, i] = 0 for j in range(i, N_LINKS): J[0, i] -= link_lengths[j] * np.sin(np.sum(joint_angles[:j])) J[1, i] += link_lengths[j] * np.cos(np.sum(joint_angles[:j])) return np.linalg.pinv(J)
1,458
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py
distance_to_goal
(current_pos, goal_pos)
return np.array([x_diff, y_diff]).T, np.hypot(x_diff, y_diff)
152
155
def distance_to_goal(current_pos, goal_pos): x_diff = goal_pos[0] - current_pos[0] y_diff = goal_pos[1] - current_pos[1] return np.array([x_diff, y_diff]).T, np.hypot(x_diff, y_diff)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py#L152-L155
2
[ 0, 1, 2, 3 ]
100
[]
0
true
93.82716
4
1
100
0
def distance_to_goal(current_pos, goal_pos): x_diff = goal_pos[0] - current_pos[0] y_diff = goal_pos[1] - current_pos[1] return np.array([x_diff, y_diff]).T, np.hypot(x_diff, y_diff)
1,459
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py
ang_diff
(theta1, theta2)
return (theta1 - theta2 + np.pi) % (2 * np.pi) - np.pi
Returns the difference between two angles in the range -pi to +pi
Returns the difference between two angles in the range -pi to +pi
158
162
def ang_diff(theta1, theta2): """ Returns the difference between two angles in the range -pi to +pi """ return (theta1 - theta2 + np.pi) % (2 * np.pi) - np.pi
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py#L158-L162
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
93.82716
5
1
100
1
def ang_diff(theta1, theta2): return (theta1 - theta2 + np.pi) % (2 * np.pi) - np.pi
1,460
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py
NLinkArm.__init__
(self, link_lengths, joint_angles, goal, show_animation)
12
32
def __init__(self, link_lengths, joint_angles, goal, show_animation): self.show_animation = show_animation self.n_links = len(link_lengths) if self.n_links != len(joint_angles): raise ValueError() self.link_lengths = np.array(link_lengths) self.joint_angles = np.array(joint_angles) self.points = [[0, 0] for _ in range(self.n_links + 1)] self.lim = sum(link_lengths) self.goal = np.array(goal).T if show_animation: # pragma: no cover self.fig = plt.figure() self.fig.canvas.mpl_connect('button_press_event', self.click) plt.ion() plt.show() self.update_points()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py#L12-L32
2
[ 0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 19, 20 ]
87.5
[ 4 ]
6.25
false
88
21
4
93.75
0
def __init__(self, link_lengths, joint_angles, goal, show_animation): self.show_animation = show_animation self.n_links = len(link_lengths) if self.n_links != len(joint_angles): raise ValueError() self.link_lengths = np.array(link_lengths) self.joint_angles = np.array(joint_angles) self.points = [[0, 0] for _ in range(self.n_links + 1)] self.lim = sum(link_lengths) self.goal = np.array(goal).T if show_animation: # pragma: no cover self.fig = plt.figure() self.fig.canvas.mpl_connect('button_press_event', self.click) plt.ion() plt.show() self.update_points()
1,461
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py
NLinkArm.update_joints
(self, joint_angles)
34
37
def update_joints(self, joint_angles): self.joint_angles = joint_angles self.update_points()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py#L34-L37
2
[ 0, 1, 2, 3 ]
100
[]
0
true
88
4
1
100
0
def update_joints(self, joint_angles): self.joint_angles = joint_angles self.update_points()
1,462
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py
NLinkArm.update_points
(self)
39
50
def update_points(self): for i in range(1, self.n_links + 1): self.points[i][0] = self.points[i - 1][0] + \ self.link_lengths[i - 1] * \ np.cos(np.sum(self.joint_angles[:i])) self.points[i][1] = self.points[i - 1][1] + \ self.link_lengths[i - 1] * \ np.sin(np.sum(self.joint_angles[:i])) self.end_effector = np.array(self.points[self.n_links]).T if self.show_animation: # pragma: no cover self.plot()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py#L39-L50
2
[ 0, 1, 2, 5, 8, 9 ]
60
[]
0
false
88
12
3
100
0
def update_points(self): for i in range(1, self.n_links + 1): self.points[i][0] = self.points[i - 1][0] + \ self.link_lengths[i - 1] * \ np.cos(np.sum(self.joint_angles[:i])) self.points[i][1] = self.points[i - 1][1] + \ self.link_lengths[i - 1] * \ np.sin(np.sum(self.joint_angles[:i])) self.end_effector = np.array(self.points[self.n_links]).T if self.show_animation: # pragma: no cover self.plot()
1,463
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py
NLinkArm.plot
(self)
52
72
def plot(self): # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) for i in range(self.n_links + 1): if i is not self.n_links: plt.plot([self.points[i][0], self.points[i + 1][0]], [self.points[i][1], self.points[i + 1][1]], 'r-') plt.plot(self.points[i][0], self.points[i][1], 'ko') plt.plot(self.goal[0], self.goal[1], 'gx') plt.plot([self.end_effector[0], self.goal[0]], [ self.end_effector[1], self.goal[1]], 'g--') plt.xlim([-self.lim, self.lim]) plt.ylim([-self.lim, self.lim]) plt.draw() plt.pause(0.0001)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py#L52-L72
2
[]
0
[]
0
false
88
21
3
100
0
def plot(self): # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) for i in range(self.n_links + 1): if i is not self.n_links: plt.plot([self.points[i][0], self.points[i + 1][0]], [self.points[i][1], self.points[i + 1][1]], 'r-') plt.plot(self.points[i][0], self.points[i][1], 'ko') plt.plot(self.goal[0], self.goal[1], 'gx') plt.plot([self.end_effector[0], self.goal[0]], [ self.end_effector[1], self.goal[1]], 'g--') plt.xlim([-self.lim, self.lim]) plt.ylim([-self.lim, self.lim]) plt.draw() plt.pause(0.0001)
1,464
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py
NLinkArm.click
(self, event)
74
76
def click(self, event): self.goal = np.array([event.xdata, event.ydata]).T self.plot()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py#L74-L76
2
[ 0 ]
33.333333
[ 1, 2 ]
66.666667
false
88
3
1
33.333333
0
def click(self, event): self.goal = np.array([event.xdata, event.ydata]).T self.plot()
1,465
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
Link.__init__
(self, dh_params)
12
13
def __init__(self, dh_params): self.dh_params_ = dh_params
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L12-L13
2
[ 0, 1 ]
100
[]
0
true
24.305556
2
1
100
0
def __init__(self, dh_params): self.dh_params_ = dh_params
1,468
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
Link.transformation_matrix
(self)
return trans
15
30
def transformation_matrix(self): theta = self.dh_params_[0] alpha = self.dh_params_[1] a = self.dh_params_[2] d = self.dh_params_[3] st = math.sin(theta) ct = math.cos(theta) sa = math.sin(alpha) ca = math.cos(alpha) trans = np.array([[ct, -st * ca, st * sa, a * ct], [st, ct * ca, -ct * sa, a * st], [0, sa, ca, d], [0, 0, 0, 1]]) return trans
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L15-L30
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15 ]
81.25
[]
0
false
24.305556
16
1
100
0
def transformation_matrix(self): theta = self.dh_params_[0] alpha = self.dh_params_[1] a = self.dh_params_[2] d = self.dh_params_[3] st = math.sin(theta) ct = math.cos(theta) sa = math.sin(alpha) ca = math.cos(alpha) trans = np.array([[ct, -st * ca, st * sa, a * ct], [st, ct * ca, -ct * sa, a * st], [0, sa, ca, d], [0, 0, 0, 1]]) return trans
1,469
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
Link.basic_jacobian
(trans_prev, ee_pos)
return basic_jacobian
33
41
def basic_jacobian(trans_prev, ee_pos): pos_prev = np.array( [trans_prev[0, 3], trans_prev[1, 3], trans_prev[2, 3]]) z_axis_prev = np.array( [trans_prev[0, 2], trans_prev[1, 2], trans_prev[2, 2]]) basic_jacobian = np.hstack( (np.cross(z_axis_prev, ee_pos - pos_prev), z_axis_prev)) return basic_jacobian
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L33-L41
2
[ 0 ]
11.111111
[ 1, 3, 6, 8 ]
44.444444
false
24.305556
9
1
55.555556
0
def basic_jacobian(trans_prev, ee_pos): pos_prev = np.array( [trans_prev[0, 3], trans_prev[1, 3], trans_prev[2, 3]]) z_axis_prev = np.array( [trans_prev[0, 2], trans_prev[1, 2], trans_prev[2, 2]]) basic_jacobian = np.hstack( (np.cross(z_axis_prev, ee_pos - pos_prev), z_axis_prev)) return basic_jacobian
1,470
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
NLinkArm.__init__
(self, dh_params_list)
45
48
def __init__(self, dh_params_list): self.link_list = [] for i in range(len(dh_params_list)): self.link_list.append(Link(dh_params_list[i]))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L45-L48
2
[ 0, 1, 2, 3 ]
100
[]
0
true
24.305556
4
2
100
0
def __init__(self, dh_params_list): self.link_list = [] for i in range(len(dh_params_list)): self.link_list.append(Link(dh_params_list[i]))
1,471
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
NLinkArm.transformation_matrix
(self)
return trans
50
54
def transformation_matrix(self): trans = np.identity(4) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) return trans
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L50-L54
2
[ 0 ]
20
[ 1, 2, 3, 4 ]
80
false
24.305556
5
2
20
0
def transformation_matrix(self): trans = np.identity(4) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) return trans
1,472
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
NLinkArm.forward_kinematics
(self, plot=False)
return [x, y, z, alpha, beta, gamma]
56
94
def forward_kinematics(self, plot=False): trans = self.transformation_matrix() x = trans[0, 3] y = trans[1, 3] z = trans[2, 3] alpha, beta, gamma = self.euler_angle() if plot: self.fig = plt.figure() self.ax = Axes3D(self.fig, auto_add_to_figure=False) self.fig.add_axes(self.ax) x_list = [] y_list = [] z_list = [] trans = np.identity(4) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) self.ax.plot(x_list, y_list, z_list, "o-", color="#00aa00", ms=4, mew=0.5) self.ax.plot([0], [0], [0], "o") self.ax.set_xlim(-1, 1) self.ax.set_ylim(-1, 1) self.ax.set_zlim(-1, 1) plt.show() return [x, y, z, alpha, beta, gamma]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L56-L94
2
[ 0 ]
2.564103
[ 1, 3, 4, 5, 6, 8, 9, 10, 11, 13, 14, 15, 17, 19, 20, 21, 22, 23, 24, 25, 26, 28, 30, 32, 33, 34, 36, 38 ]
71.794872
false
24.305556
39
3
28.205128
0
def forward_kinematics(self, plot=False): trans = self.transformation_matrix() x = trans[0, 3] y = trans[1, 3] z = trans[2, 3] alpha, beta, gamma = self.euler_angle() if plot: self.fig = plt.figure() self.ax = Axes3D(self.fig, auto_add_to_figure=False) self.fig.add_axes(self.ax) x_list = [] y_list = [] z_list = [] trans = np.identity(4) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) self.ax.plot(x_list, y_list, z_list, "o-", color="#00aa00", ms=4, mew=0.5) self.ax.plot([0], [0], [0], "o") self.ax.set_xlim(-1, 1) self.ax.set_ylim(-1, 1) self.ax.set_zlim(-1, 1) plt.show() return [x, y, z, alpha, beta, gamma]
1,473
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
NLinkArm.basic_jacobian
(self)
return np.array(basic_jacobian_mat).T
96
106
def basic_jacobian(self): ee_pos = self.forward_kinematics()[0:3] basic_jacobian_mat = [] trans = np.identity(4) for i in range(len(self.link_list)): basic_jacobian_mat.append( self.link_list[i].basic_jacobian(trans, ee_pos)) trans = np.dot(trans, self.link_list[i].transformation_matrix()) return np.array(basic_jacobian_mat).T
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L96-L106
2
[ 0 ]
9.090909
[ 1, 2, 4, 5, 6, 8, 10 ]
63.636364
false
24.305556
11
2
36.363636
0
def basic_jacobian(self): ee_pos = self.forward_kinematics()[0:3] basic_jacobian_mat = [] trans = np.identity(4) for i in range(len(self.link_list)): basic_jacobian_mat.append( self.link_list[i].basic_jacobian(trans, ee_pos)) trans = np.dot(trans, self.link_list[i].transformation_matrix()) return np.array(basic_jacobian_mat).T
1,474
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
NLinkArm.inverse_kinematics
(self, ref_ee_pose, plot=False)
108
157
def inverse_kinematics(self, ref_ee_pose, plot=False): for cnt in range(500): ee_pose = self.forward_kinematics() diff_pose = np.array(ref_ee_pose) - ee_pose basic_jacobian_mat = self.basic_jacobian() alpha, beta, gamma = self.euler_angle() K_zyz = np.array( [[0, -math.sin(alpha), math.cos(alpha) * math.sin(beta)], [0, math.cos(alpha), math.sin(alpha) * math.sin(beta)], [1, 0, math.cos(beta)]]) K_alpha = np.identity(6) K_alpha[3:, 3:] = K_zyz theta_dot = np.dot( np.dot(np.linalg.pinv(basic_jacobian_mat), K_alpha), np.array(diff_pose)) self.update_joint_angles(theta_dot / 100.) if plot: self.fig = plt.figure() self.ax = Axes3D(self.fig) x_list = [] y_list = [] z_list = [] trans = np.identity(4) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) self.ax.plot(x_list, y_list, z_list, "o-", color="#00aa00", ms=4, mew=0.5) self.ax.plot([0], [0], [0], "o") self.ax.set_xlim(-1, 1) self.ax.set_ylim(-1, 1) self.ax.set_zlim(-1, 1) self.ax.plot([ref_ee_pose[0]], [ref_ee_pose[1]], [ref_ee_pose[2]], "o") plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L108-L157
2
[ 0 ]
2
[ 1, 2, 3, 5, 6, 8, 12, 13, 15, 18, 20, 21, 22, 24, 25, 26, 28, 30, 31, 32, 33, 34, 35, 36, 37, 39, 41, 43, 44, 45, 47, 49 ]
64
false
24.305556
50
4
36
0
def inverse_kinematics(self, ref_ee_pose, plot=False): for cnt in range(500): ee_pose = self.forward_kinematics() diff_pose = np.array(ref_ee_pose) - ee_pose basic_jacobian_mat = self.basic_jacobian() alpha, beta, gamma = self.euler_angle() K_zyz = np.array( [[0, -math.sin(alpha), math.cos(alpha) * math.sin(beta)], [0, math.cos(alpha), math.sin(alpha) * math.sin(beta)], [1, 0, math.cos(beta)]]) K_alpha = np.identity(6) K_alpha[3:, 3:] = K_zyz theta_dot = np.dot( np.dot(np.linalg.pinv(basic_jacobian_mat), K_alpha), np.array(diff_pose)) self.update_joint_angles(theta_dot / 100.) if plot: self.fig = plt.figure() self.ax = Axes3D(self.fig) x_list = [] y_list = [] z_list = [] trans = np.identity(4) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) self.ax.plot(x_list, y_list, z_list, "o-", color="#00aa00", ms=4, mew=0.5) self.ax.plot([0], [0], [0], "o") self.ax.set_xlim(-1, 1) self.ax.set_ylim(-1, 1) self.ax.set_zlim(-1, 1) self.ax.plot([ref_ee_pose[0]], [ref_ee_pose[1]], [ref_ee_pose[2]], "o") plt.show()
1,475
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
NLinkArm.euler_angle
(self)
return alpha, beta, gamma
159
174
def euler_angle(self): trans = self.transformation_matrix() alpha = math.atan2(trans[1][2], trans[0][2]) if not (-math.pi / 2 <= alpha <= math.pi / 2): alpha = math.atan2(trans[1][2], trans[0][2]) + math.pi if not (-math.pi / 2 <= alpha <= math.pi / 2): alpha = math.atan2(trans[1][2], trans[0][2]) - math.pi beta = math.atan2( trans[0][2] * math.cos(alpha) + trans[1][2] * math.sin(alpha), trans[2][2]) gamma = math.atan2( -trans[0][0] * math.sin(alpha) + trans[1][0] * math.cos(alpha), -trans[0][1] * math.sin(alpha) + trans[1][1] * math.cos(alpha)) return alpha, beta, gamma
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L159-L174
2
[ 0 ]
6.25
[ 1, 3, 4, 5, 6, 7, 8, 11, 15 ]
56.25
false
24.305556
16
3
43.75
0
def euler_angle(self): trans = self.transformation_matrix() alpha = math.atan2(trans[1][2], trans[0][2]) if not (-math.pi / 2 <= alpha <= math.pi / 2): alpha = math.atan2(trans[1][2], trans[0][2]) + math.pi if not (-math.pi / 2 <= alpha <= math.pi / 2): alpha = math.atan2(trans[1][2], trans[0][2]) - math.pi beta = math.atan2( trans[0][2] * math.cos(alpha) + trans[1][2] * math.sin(alpha), trans[2][2]) gamma = math.atan2( -trans[0][0] * math.sin(alpha) + trans[1][0] * math.cos(alpha), -trans[0][1] * math.sin(alpha) + trans[1][1] * math.cos(alpha)) return alpha, beta, gamma
1,476
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
NLinkArm.set_joint_angles
(self, joint_angle_list)
176
178
def set_joint_angles(self, joint_angle_list): for i in range(len(self.link_list)): self.link_list[i].dh_params_[0] = joint_angle_list[i]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L176-L178
2
[ 0, 1, 2 ]
100
[]
0
true
24.305556
3
2
100
0
def set_joint_angles(self, joint_angle_list): for i in range(len(self.link_list)): self.link_list[i].dh_params_[0] = joint_angle_list[i]
1,477
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
NLinkArm.update_joint_angles
(self, diff_joint_angle_list)
180
182
def update_joint_angles(self, diff_joint_angle_list): for i in range(len(self.link_list)): self.link_list[i].dh_params_[0] += diff_joint_angle_list[i]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L180-L182
2
[ 0 ]
33.333333
[ 1, 2 ]
66.666667
false
24.305556
3
2
33.333333
0
def update_joint_angles(self, diff_joint_angle_list): for i in range(len(self.link_list)): self.link_list[i].dh_params_[0] += diff_joint_angle_list[i]
1,478
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_3d/NLinkArm3d.py
NLinkArm.plot
(self)
184
214
def plot(self): self.fig = plt.figure() self.ax = Axes3D(self.fig) x_list = [] y_list = [] z_list = [] trans = np.identity(4) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) self.ax.plot(x_list, y_list, z_list, "o-", color="#00aa00", ms=4, mew=0.5) self.ax.plot([0], [0], [0], "o") self.ax.set_xlabel("x") self.ax.set_ylabel("y") self.ax.set_zlabel("z") self.ax.set_xlim(-1, 1) self.ax.set_ylim(-1, 1) self.ax.set_zlim(-1, 1) plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py#L184-L214
2
[ 0 ]
3.225806
[ 1, 2, 4, 5, 6, 8, 10, 11, 12, 13, 14, 15, 16, 17, 19, 21, 23, 24, 25, 27, 28, 29, 30 ]
74.193548
false
24.305556
31
2
25.806452
0
def plot(self): self.fig = plt.figure() self.ax = Axes3D(self.fig) x_list = [] y_list = [] z_list = [] trans = np.identity(4) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) self.ax.plot(x_list, y_list, z_list, "o-", color="#00aa00", ms=4, mew=0.5) self.ax.plot([0], [0], [0], "o") self.ax.set_xlabel("x") self.ax.set_ylabel("y") self.ax.set_zlabel("z") self.ax.set_xlim(-1, 1) self.ax.set_ylim(-1, 1) self.ax.set_zlim(-1, 1) plt.show()
1,479
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py
two_joint_arm
(GOAL_TH=0.0, theta1=0.0, theta2=0.0)
Computes the inverse kinematics for a planar 2DOF arm When out of bounds, rewrite x and y with last correct values
Computes the inverse kinematics for a planar 2DOF arm When out of bounds, rewrite x and y with last correct values
36
79
def two_joint_arm(GOAL_TH=0.0, theta1=0.0, theta2=0.0): """ Computes the inverse kinematics for a planar 2DOF arm When out of bounds, rewrite x and y with last correct values """ global x, y x_prev, y_prev = None, None while True: try: if x is not None and y is not None: x_prev = x y_prev = y if np.sqrt(x**2 + y**2) > (l1 + l2): theta2_goal = 0 else: theta2_goal = np.arccos( (x**2 + y**2 - l1**2 - l2**2) / (2 * l1 * l2)) tmp = np.math.atan2(l2 * np.sin(theta2_goal), (l1 + l2 * np.cos(theta2_goal))) theta1_goal = np.math.atan2(y, x) - tmp if theta1_goal < 0: theta2_goal = -theta2_goal tmp = np.math.atan2(l2 * np.sin(theta2_goal), (l1 + l2 * np.cos(theta2_goal))) theta1_goal = np.math.atan2(y, x) - tmp theta1 = theta1 + Kp * ang_diff(theta1_goal, theta1) * dt theta2 = theta2 + Kp * ang_diff(theta2_goal, theta2) * dt except ValueError as e: print("Unreachable goal"+e) except TypeError: x = x_prev y = y_prev wrist = plot_arm(theta1, theta2, x, y) # check goal d2goal = None if x is not None and y is not None: d2goal = np.hypot(wrist[0] - x, wrist[1] - y) if abs(d2goal) < GOAL_TH and x is not None: return theta1, theta2
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py#L36-L79
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43 ]
86.363636
[ 13, 29, 30, 31, 32, 33 ]
13.636364
false
86
44
12
86.363636
2
def two_joint_arm(GOAL_TH=0.0, theta1=0.0, theta2=0.0): global x, y x_prev, y_prev = None, None while True: try: if x is not None and y is not None: x_prev = x y_prev = y if np.sqrt(x**2 + y**2) > (l1 + l2): theta2_goal = 0 else: theta2_goal = np.arccos( (x**2 + y**2 - l1**2 - l2**2) / (2 * l1 * l2)) tmp = np.math.atan2(l2 * np.sin(theta2_goal), (l1 + l2 * np.cos(theta2_goal))) theta1_goal = np.math.atan2(y, x) - tmp if theta1_goal < 0: theta2_goal = -theta2_goal tmp = np.math.atan2(l2 * np.sin(theta2_goal), (l1 + l2 * np.cos(theta2_goal))) theta1_goal = np.math.atan2(y, x) - tmp theta1 = theta1 + Kp * ang_diff(theta1_goal, theta1) * dt theta2 = theta2 + Kp * ang_diff(theta2_goal, theta2) * dt except ValueError as e: print("Unreachable goal"+e) except TypeError: x = x_prev y = y_prev wrist = plot_arm(theta1, theta2, x, y) # check goal d2goal = None if x is not None and y is not None: d2goal = np.hypot(wrist[0] - x, wrist[1] - y) if abs(d2goal) < GOAL_TH and x is not None: return theta1, theta2
1,482
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py
plot_arm
(theta1, theta2, target_x, target_y)
return wrist
82
107
def plot_arm(theta1, theta2, target_x, target_y): # pragma: no cover shoulder = np.array([0, 0]) elbow = shoulder + np.array([l1 * np.cos(theta1), l1 * np.sin(theta1)]) wrist = elbow + \ np.array([l2 * np.cos(theta1 + theta2), l2 * np.sin(theta1 + theta2)]) if show_animation: plt.cla() plt.plot([shoulder[0], elbow[0]], [shoulder[1], elbow[1]], 'k-') plt.plot([elbow[0], wrist[0]], [elbow[1], wrist[1]], 'k-') plt.plot(shoulder[0], shoulder[1], 'ro') plt.plot(elbow[0], elbow[1], 'ro') plt.plot(wrist[0], wrist[1], 'ro') plt.plot([wrist[0], target_x], [wrist[1], target_y], 'g--') plt.plot(target_x, target_y, 'g*') plt.xlim(-2, 2) plt.ylim(-2, 2) plt.show() plt.pause(dt) return wrist
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py#L82-L107
2
[]
0
[]
0
false
86
26
2
100
0
def plot_arm(theta1, theta2, target_x, target_y): # pragma: no cover shoulder = np.array([0, 0]) elbow = shoulder + np.array([l1 * np.cos(theta1), l1 * np.sin(theta1)]) wrist = elbow + \ np.array([l2 * np.cos(theta1 + theta2), l2 * np.sin(theta1 + theta2)]) if show_animation: plt.cla() plt.plot([shoulder[0], elbow[0]], [shoulder[1], elbow[1]], 'k-') plt.plot([elbow[0], wrist[0]], [elbow[1], wrist[1]], 'k-') plt.plot(shoulder[0], shoulder[1], 'ro') plt.plot(elbow[0], elbow[1], 'ro') plt.plot(wrist[0], wrist[1], 'ro') plt.plot([wrist[0], target_x], [wrist[1], target_y], 'g--') plt.plot(target_x, target_y, 'g*') plt.xlim(-2, 2) plt.ylim(-2, 2) plt.show() plt.pause(dt) return wrist
1,483
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py
ang_diff
(theta1, theta2)
return (theta1 - theta2 + np.pi) % (2 * np.pi) - np.pi
110
112
def ang_diff(theta1, theta2): # Returns the difference between two angles in the range -pi to +pi return (theta1 - theta2 + np.pi) % (2 * np.pi) - np.pi
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py#L110-L112
2
[ 0, 1, 2 ]
100
[]
0
true
86
3
1
100
0
def ang_diff(theta1, theta2): # Returns the difference between two angles in the range -pi to +pi return (theta1 - theta2 + np.pi) % (2 * np.pi) - np.pi
1,484
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py
click
(event)
115
118
def click(event): # pragma: no cover global x, y x = event.xdata y = event.ydata
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py#L115-L118
2
[]
0
[]
0
false
86
4
1
100
0
def click(event): # pragma: no cover global x, y x = event.xdata y = event.ydata
1,485
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py
animation
()
121
129
def animation(): from random import random global x, y theta1 = theta2 = 0.0 for i in range(5): x = 2.0 * random() - 1.0 y = 2.0 * random() - 1.0 theta1, theta2 = two_joint_arm( GOAL_TH=0.01, theta1=theta1, theta2=theta2)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py#L121-L129
2
[ 0, 1, 3, 4, 5, 6, 7 ]
77.777778
[]
0
false
86
9
2
100
0
def animation(): from random import random global x, y theta1 = theta2 = 0.0 for i in range(5): x = 2.0 * random() - 1.0 y = 2.0 * random() - 1.0 theta1, theta2 = two_joint_arm( GOAL_TH=0.01, theta1=theta1, theta2=theta2)
1,486
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py
main
()
132
138
def main(): # pragma: no cover fig = plt.figure() fig.canvas.mpl_connect("button_press_event", click) # for stopping simulation with the esc key. fig.canvas.mpl_connect('key_release_event', lambda event: [ exit(0) if event.key == 'escape' else None]) two_joint_arm()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py#L132-L138
2
[]
0
[]
0
false
86
7
1
100
0
def main(): # pragma: no cover fig = plt.figure() fig.canvas.mpl_connect("button_press_event", click) # for stopping simulation with the esc key. fig.canvas.mpl_connect('key_release_event', lambda event: [ exit(0) if event.key == 'escape' else None]) two_joint_arm()
1,487
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
main
()
346
401
def main(): print("Start " + __file__) # init NLinkArm with Denavit-Hartenberg parameters of panda # https://frankaemika.github.io/docs/control_parameters.html # [theta, alpha, a, d] seven_joint_arm = RobotArm([[0., math.pi/2., 0., .333], [0., -math.pi/2., 0., 0.], [0., math.pi/2., 0.0825, 0.3160], [0., -math.pi/2., -0.0825, 0.], [0., math.pi/2., 0., 0.3840], [0., math.pi/2., 0.088, 0.], [0., 0., 0., 0.107]]) # ====Search Path with RRT==== obstacle_list = [ (-.3, -.3, .7, .1), (.0, -.3, .7, .1), (.2, -.1, .3, .15), ] # [x,y,size(radius)] start = [0 for _ in range(len(seven_joint_arm.link_list))] end = [1.5 for _ in range(len(seven_joint_arm.link_list))] # Set Initial parameters rrt_star = RRTStar(start=start, goal=end, rand_area=[0, 2], max_iter=200, robot=seven_joint_arm, obstacle_list=obstacle_list) path = rrt_star.planning(animation=show_animation, search_until_max_iter=False) if path is None: print("Cannot find path") else: print("found path!!") # Draw final path if show_animation: ax = rrt_star.draw_graph() # Plot final configuration x_points, y_points, z_points = seven_joint_arm.get_points(path[-1]) ax.plot([x for x in x_points], [y for y in y_points], [z for z in z_points], "o-", color="red", ms=5, mew=0.5) for i, q in enumerate(path): x_points, y_points, z_points = seven_joint_arm.get_points(q) ax.plot([x for x in x_points], [y for y in y_points], [z for z in z_points], "o-", color="grey", ms=4, mew=0.5) plt.pause(0.01) plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L346-L401
2
[ 0, 1, 2, 3, 4, 5, 6, 13, 14, 19, 20, 21, 22, 28, 30, 31, 34, 35, 36, 37 ]
35.714286
[ 32, 38, 41, 42, 47, 48, 49, 53, 55 ]
16.071429
false
76.264591
56
12
83.928571
0
def main(): print("Start " + __file__) # init NLinkArm with Denavit-Hartenberg parameters of panda # https://frankaemika.github.io/docs/control_parameters.html # [theta, alpha, a, d] seven_joint_arm = RobotArm([[0., math.pi/2., 0., .333], [0., -math.pi/2., 0., 0.], [0., math.pi/2., 0.0825, 0.3160], [0., -math.pi/2., -0.0825, 0.], [0., math.pi/2., 0., 0.3840], [0., math.pi/2., 0.088, 0.], [0., 0., 0., 0.107]]) # ====Search Path with RRT==== obstacle_list = [ (-.3, -.3, .7, .1), (.0, -.3, .7, .1), (.2, -.1, .3, .15), ] # [x,y,size(radius)] start = [0 for _ in range(len(seven_joint_arm.link_list))] end = [1.5 for _ in range(len(seven_joint_arm.link_list))] # Set Initial parameters rrt_star = RRTStar(start=start, goal=end, rand_area=[0, 2], max_iter=200, robot=seven_joint_arm, obstacle_list=obstacle_list) path = rrt_star.planning(animation=show_animation, search_until_max_iter=False) if path is None: print("Cannot find path") else: print("found path!!") # Draw final path if show_animation: ax = rrt_star.draw_graph() # Plot final configuration x_points, y_points, z_points = seven_joint_arm.get_points(path[-1]) ax.plot([x for x in x_points], [y for y in y_points], [z for z in z_points], "o-", color="red", ms=5, mew=0.5) for i, q in enumerate(path): x_points, y_points, z_points = seven_joint_arm.get_points(q) ax.plot([x for x in x_points], [y for y in y_points], [z for z in z_points], "o-", color="grey", ms=4, mew=0.5) plt.pause(0.01) plt.show()
1,488
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RobotArm.get_points
(self, joint_angle_list)
return x_list, y_list, z_list
21
39
def get_points(self, joint_angle_list): self.set_joint_angles(joint_angle_list) x_list = [] y_list = [] z_list = [] trans = np.identity(4) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) return x_list, y_list, z_list
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L21-L39
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
76.264591
19
2
100
0
def get_points(self, joint_angle_list): self.set_joint_angles(joint_angle_list) x_list = [] y_list = [] z_list = [] trans = np.identity(4) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) for i in range(len(self.link_list)): trans = np.dot(trans, self.link_list[i].transformation_matrix()) x_list.append(trans[0, 3]) y_list.append(trans[1, 3]) z_list.append(trans[2, 3]) return x_list, y_list, z_list
1,489
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.__init__
(self, start, goal, robot, obstacle_list, rand_area, expand_dis=.30, path_resolution=.1, goal_sample_rate=20, max_iter=300, connect_circle_dist=50.0 )
Setting Parameter start:Start Position [q1,...,qn] goal:Goal Position [q1,...,qn] obstacleList:obstacle Positions [[x,y,z,size],...] randArea:Random Sampling Area [min,max]
Setting Parameter
53
83
def __init__(self, start, goal, robot, obstacle_list, rand_area, expand_dis=.30, path_resolution=.1, goal_sample_rate=20, max_iter=300, connect_circle_dist=50.0 ): """ Setting Parameter start:Start Position [q1,...,qn] goal:Goal Position [q1,...,qn] obstacleList:obstacle Positions [[x,y,z,size],...] randArea:Random Sampling Area [min,max] """ self.start = self.Node(start) self.end = self.Node(goal) self.dimension = len(start) self.min_rand = rand_area[0] self.max_rand = rand_area[1] self.expand_dis = expand_dis self.path_resolution = path_resolution self.goal_sample_rate = goal_sample_rate self.max_iter = max_iter self.robot = robot self.obstacle_list = obstacle_list self.connect_circle_dist = connect_circle_dist self.goal_node = self.Node(goal) self.ax = plt.axes(projection='3d') self.node_list = []
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L53-L83
2
[ 0, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ]
54.83871
[]
0
false
76.264591
31
1
100
6
def __init__(self, start, goal, robot, obstacle_list, rand_area, expand_dis=.30, path_resolution=.1, goal_sample_rate=20, max_iter=300, connect_circle_dist=50.0 ): self.start = self.Node(start) self.end = self.Node(goal) self.dimension = len(start) self.min_rand = rand_area[0] self.max_rand = rand_area[1] self.expand_dis = expand_dis self.path_resolution = path_resolution self.goal_sample_rate = goal_sample_rate self.max_iter = max_iter self.robot = robot self.obstacle_list = obstacle_list self.connect_circle_dist = connect_circle_dist self.goal_node = self.Node(goal) self.ax = plt.axes(projection='3d') self.node_list = []
1,490
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.planning
(self, animation=False, search_until_max_iter=False)
return None
rrt star path planning animation: flag for animation on or off search_until_max_iter: search until max iteration for path improving or not
rrt star path planning
85
125
def planning(self, animation=False, search_until_max_iter=False): """ rrt star path planning animation: flag for animation on or off search_until_max_iter: search until max iteration for path improving or not """ self.node_list = [self.start] for i in range(self.max_iter): if verbose: print("Iter:", i, ", number of nodes:", len(self.node_list)) rnd = self.get_random_node() nearest_ind = self.get_nearest_node_index(self.node_list, rnd) new_node = self.steer(self.node_list[nearest_ind], rnd, self.expand_dis) if self.check_collision(new_node, self.robot, self.obstacle_list): near_inds = self.find_near_nodes(new_node) new_node = self.choose_parent(new_node, near_inds) if new_node: self.node_list.append(new_node) self.rewire(new_node, near_inds) if animation and i % 5 == 0 and self.dimension <= 3: self.draw_graph(rnd) if (not search_until_max_iter) and new_node: last_index = self.search_best_goal_node() if last_index is not None: return self.generate_final_course(last_index) if verbose: print("reached max iteration") last_index = self.search_best_goal_node() if last_index is not None: return self.generate_final_course(last_index) return None
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L85-L125
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32 ]
75.609756
[ 12, 27, 33, 34, 36, 37, 38, 40 ]
19.512195
false
76.264591
41
13
80.487805
5
def planning(self, animation=False, search_until_max_iter=False): self.node_list = [self.start] for i in range(self.max_iter): if verbose: print("Iter:", i, ", number of nodes:", len(self.node_list)) rnd = self.get_random_node() nearest_ind = self.get_nearest_node_index(self.node_list, rnd) new_node = self.steer(self.node_list[nearest_ind], rnd, self.expand_dis) if self.check_collision(new_node, self.robot, self.obstacle_list): near_inds = self.find_near_nodes(new_node) new_node = self.choose_parent(new_node, near_inds) if new_node: self.node_list.append(new_node) self.rewire(new_node, near_inds) if animation and i % 5 == 0 and self.dimension <= 3: self.draw_graph(rnd) if (not search_until_max_iter) and new_node: last_index = self.search_best_goal_node() if last_index is not None: return self.generate_final_course(last_index) if verbose: print("reached max iteration") last_index = self.search_best_goal_node() if last_index is not None: return self.generate_final_course(last_index) return None
1,491
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.choose_parent
(self, new_node, near_inds)
return new_node
127
153
def choose_parent(self, new_node, near_inds): if not near_inds: return None # search nearest cost in near_inds costs = [] for i in near_inds: near_node = self.node_list[i] t_node = self.steer(near_node, new_node) if t_node and self.check_collision(t_node, self.robot, self.obstacle_list): costs.append(self.calc_new_cost(near_node, new_node)) else: costs.append(float("inf")) # the cost of collision node min_cost = min(costs) if min_cost == float("inf"): print("There is no good path.(min_cost is inf)") return None min_ind = near_inds[costs.index(min_cost)] new_node = self.steer(self.node_list[min_ind], new_node) new_node.parent = self.node_list[min_ind] new_node.cost = min_cost return new_node
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L127-L153
2
[ 0, 1, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 20, 21, 22, 23, 24, 25, 26 ]
70.37037
[ 2, 14, 18, 19 ]
14.814815
false
76.264591
27
6
85.185185
0
def choose_parent(self, new_node, near_inds): if not near_inds: return None # search nearest cost in near_inds costs = [] for i in near_inds: near_node = self.node_list[i] t_node = self.steer(near_node, new_node) if t_node and self.check_collision(t_node, self.robot, self.obstacle_list): costs.append(self.calc_new_cost(near_node, new_node)) else: costs.append(float("inf")) # the cost of collision node min_cost = min(costs) if min_cost == float("inf"): print("There is no good path.(min_cost is inf)") return None min_ind = near_inds[costs.index(min_cost)] new_node = self.steer(self.node_list[min_ind], new_node) new_node.parent = self.node_list[min_ind] new_node.cost = min_cost return new_node
1,492
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.search_best_goal_node
(self)
return None
155
175
def search_best_goal_node(self): dist_to_goal_list = [self.calc_dist_to_goal(n.x) for n in self.node_list] goal_inds = [dist_to_goal_list.index(i) for i in dist_to_goal_list if i <= self.expand_dis] safe_goal_inds = [] for goal_ind in goal_inds: t_node = self.steer(self.node_list[goal_ind], self.goal_node) if self.check_collision(t_node, self.robot, self.obstacle_list): safe_goal_inds.append(goal_ind) if not safe_goal_inds: return None min_cost = min([self.node_list[i].cost for i in safe_goal_inds]) for i in safe_goal_inds: if self.node_list[i].cost == min_cost: return i return None
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L155-L175
2
[ 0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
85.714286
[ 20 ]
4.761905
false
76.264591
21
9
95.238095
0
def search_best_goal_node(self): dist_to_goal_list = [self.calc_dist_to_goal(n.x) for n in self.node_list] goal_inds = [dist_to_goal_list.index(i) for i in dist_to_goal_list if i <= self.expand_dis] safe_goal_inds = [] for goal_ind in goal_inds: t_node = self.steer(self.node_list[goal_ind], self.goal_node) if self.check_collision(t_node, self.robot, self.obstacle_list): safe_goal_inds.append(goal_ind) if not safe_goal_inds: return None min_cost = min([self.node_list[i].cost for i in safe_goal_inds]) for i in safe_goal_inds: if self.node_list[i].cost == min_cost: return i return None
1,493
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.find_near_nodes
(self, new_node)
return near_inds
177
187
def find_near_nodes(self, new_node): nnode = len(self.node_list) + 1 r = self.connect_circle_dist * math.sqrt((math.log(nnode) / nnode)) # if expand_dist exists, search vertices in # a range no more than expand_dist if hasattr(self, 'expand_dis'): r = min(r, self.expand_dis) dist_list = [np.sum((np.array(node.x) - np.array(new_node.x)) ** 2) for node in self.node_list] near_inds = [dist_list.index(i) for i in dist_list if i <= r ** 2] return near_inds
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L177-L187
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 9, 10 ]
90.909091
[]
0
false
76.264591
11
4
100
0
def find_near_nodes(self, new_node): nnode = len(self.node_list) + 1 r = self.connect_circle_dist * math.sqrt((math.log(nnode) / nnode)) # if expand_dist exists, search vertices in # a range no more than expand_dist if hasattr(self, 'expand_dis'): r = min(r, self.expand_dis) dist_list = [np.sum((np.array(node.x) - np.array(new_node.x)) ** 2) for node in self.node_list] near_inds = [dist_list.index(i) for i in dist_list if i <= r ** 2] return near_inds
1,494
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.rewire
(self, new_node, near_inds)
189
204
def rewire(self, new_node, near_inds): for i in near_inds: near_node = self.node_list[i] edge_node = self.steer(new_node, near_node) if not edge_node: continue edge_node.cost = self.calc_new_cost(new_node, near_node) no_collision = self.check_collision(edge_node, self.robot, self.obstacle_list) improved_cost = near_node.cost > edge_node.cost if no_collision and improved_cost: self.node_list[i] = edge_node self.propagate_cost_to_leaves(new_node)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L189-L204
2
[ 0, 1, 2, 3, 4, 6, 7, 8, 11, 12, 13 ]
68.75
[ 5, 14, 15 ]
18.75
false
76.264591
16
5
81.25
0
def rewire(self, new_node, near_inds): for i in near_inds: near_node = self.node_list[i] edge_node = self.steer(new_node, near_node) if not edge_node: continue edge_node.cost = self.calc_new_cost(new_node, near_node) no_collision = self.check_collision(edge_node, self.robot, self.obstacle_list) improved_cost = near_node.cost > edge_node.cost if no_collision and improved_cost: self.node_list[i] = edge_node self.propagate_cost_to_leaves(new_node)
1,495
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.calc_new_cost
(self, from_node, to_node)
return from_node.cost + d
206
208
def calc_new_cost(self, from_node, to_node): d, _, _ = self.calc_distance_and_angle(from_node, to_node) return from_node.cost + d
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L206-L208
2
[ 0, 1, 2 ]
100
[]
0
true
76.264591
3
1
100
0
def calc_new_cost(self, from_node, to_node): d, _, _ = self.calc_distance_and_angle(from_node, to_node) return from_node.cost + d
1,496
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.propagate_cost_to_leaves
(self, parent_node)
210
215
def propagate_cost_to_leaves(self, parent_node): for node in self.node_list: if node.parent == parent_node: node.cost = self.calc_new_cost(parent_node, node) self.propagate_cost_to_leaves(node)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L210-L215
2
[ 0, 1 ]
33.333333
[ 2, 3, 4, 5 ]
66.666667
false
76.264591
6
3
33.333333
0
def propagate_cost_to_leaves(self, parent_node): for node in self.node_list: if node.parent == parent_node: node.cost = self.calc_new_cost(parent_node, node) self.propagate_cost_to_leaves(node)
1,497
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.generate_final_course
(self, goal_ind)
return path
217
225
def generate_final_course(self, goal_ind): path = [self.end.x] node = self.node_list[goal_ind] while node.parent is not None: path.append(node.x) node = node.parent path.append(node.x) reversed(path) return path
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L217-L225
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
76.264591
9
2
100
0
def generate_final_course(self, goal_ind): path = [self.end.x] node = self.node_list[goal_ind] while node.parent is not None: path.append(node.x) node = node.parent path.append(node.x) reversed(path) return path
1,498
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.calc_dist_to_goal
(self, x)
return distance
227
229
def calc_dist_to_goal(self, x): distance = np.linalg.norm(np.array(x) - np.array(self.end.x)) return distance
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L227-L229
2
[ 0, 1, 2 ]
100
[]
0
true
76.264591
3
1
100
0
def calc_dist_to_goal(self, x): distance = np.linalg.norm(np.array(x) - np.array(self.end.x)) return distance
1,499
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.get_random_node
(self)
return rnd
231
238
def get_random_node(self): if random.randint(0, 100) > self.goal_sample_rate: rnd = self.Node(np.random.uniform(self.min_rand, self.max_rand, self.dimension)) else: # goal point sampling rnd = self.Node(self.end.x) return rnd
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L231-L238
2
[ 0, 1, 2, 6, 7 ]
62.5
[]
0
false
76.264591
8
2
100
0
def get_random_node(self): if random.randint(0, 100) > self.goal_sample_rate: rnd = self.Node(np.random.uniform(self.min_rand, self.max_rand, self.dimension)) else: # goal point sampling rnd = self.Node(self.end.x) return rnd
1,500
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.steer
(self, from_node, to_node, extend_length=float("inf"))
return new_node
240
264
def steer(self, from_node, to_node, extend_length=float("inf")): new_node = self.Node(list(from_node.x)) d, phi, theta = self.calc_distance_and_angle(new_node, to_node) new_node.path_x = [list(new_node.x)] if extend_length > d: extend_length = d n_expand = math.floor(extend_length / self.path_resolution) start, end = np.array(from_node.x), np.array(to_node.x) v = end - start u = v / (np.sqrt(np.sum(v ** 2))) for _ in range(n_expand): new_node.x += u * self.path_resolution new_node.path_x.append(list(new_node.x)) d, _, _ = self.calc_distance_and_angle(new_node, to_node) if d <= self.path_resolution: new_node.path_x.append(list(to_node.x)) new_node.parent = from_node return new_node
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L240-L264
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
100
[]
0
true
76.264591
25
4
100
0
def steer(self, from_node, to_node, extend_length=float("inf")): new_node = self.Node(list(from_node.x)) d, phi, theta = self.calc_distance_and_angle(new_node, to_node) new_node.path_x = [list(new_node.x)] if extend_length > d: extend_length = d n_expand = math.floor(extend_length / self.path_resolution) start, end = np.array(from_node.x), np.array(to_node.x) v = end - start u = v / (np.sqrt(np.sum(v ** 2))) for _ in range(n_expand): new_node.x += u * self.path_resolution new_node.path_x.append(list(new_node.x)) d, _, _ = self.calc_distance_and_angle(new_node, to_node) if d <= self.path_resolution: new_node.path_x.append(list(to_node.x)) new_node.parent = from_node return new_node
1,501
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.draw_graph
(self, rnd=None)
return self.ax
266
285
def draw_graph(self, rnd=None): plt.cla() self.ax.axis([-1, 1, -1, 1]) self.ax.set_zlim(0, 1) self.ax.grid(True) for (ox, oy, oz, size) in self.obstacle_list: self.plot_sphere(self.ax, ox, oy, oz, size=size) if self.dimension > 3: return self.ax if rnd is not None: self.ax.plot([rnd.x[0]], [rnd.x[1]], [rnd.x[2]], "^k") for node in self.node_list: if node.parent: path = np.array(node.path_x) plt.plot(path[:, 0], path[:, 1], path[:, 2], "-g") self.ax.plot([self.start.x[0]], [self.start.x[1]], [self.start.x[2]], "xr") self.ax.plot([self.end.x[0]], [self.end.x[1]], [self.end.x[2]], "xr") plt.pause(0.01) return self.ax
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L266-L285
2
[ 0 ]
5
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19 ]
90
false
76.264591
20
6
10
0
def draw_graph(self, rnd=None): plt.cla() self.ax.axis([-1, 1, -1, 1]) self.ax.set_zlim(0, 1) self.ax.grid(True) for (ox, oy, oz, size) in self.obstacle_list: self.plot_sphere(self.ax, ox, oy, oz, size=size) if self.dimension > 3: return self.ax if rnd is not None: self.ax.plot([rnd.x[0]], [rnd.x[1]], [rnd.x[2]], "^k") for node in self.node_list: if node.parent: path = np.array(node.path_x) plt.plot(path[:, 0], path[:, 1], path[:, 2], "-g") self.ax.plot([self.start.x[0]], [self.start.x[1]], [self.start.x[2]], "xr") self.ax.plot([self.end.x[0]], [self.end.x[1]], [self.end.x[2]], "xr") plt.pause(0.01) return self.ax
1,502
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.get_nearest_node_index
(node_list, rnd_node)
return minind
288
293
def get_nearest_node_index(node_list, rnd_node): dlist = [np.sum((np.array(node.x) - np.array(rnd_node.x))**2) for node in node_list] minind = dlist.index(min(dlist)) return minind
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L288-L293
2
[ 0, 1, 3, 4, 5 ]
83.333333
[]
0
false
76.264591
6
2
100
0
def get_nearest_node_index(node_list, rnd_node): dlist = [np.sum((np.array(node.x) - np.array(rnd_node.x))**2) for node in node_list] minind = dlist.index(min(dlist)) return minind
1,503
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.plot_sphere
(ax, x, y, z, size=1, color="k")
296
301
def plot_sphere(ax, x, y, z, size=1, color="k"): u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j] xl = x+size*np.cos(u)*np.sin(v) yl = y+size*np.sin(u)*np.sin(v) zl = z+size*np.cos(v) ax.plot_wireframe(xl, yl, zl, color=color)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L296-L301
2
[ 0 ]
16.666667
[ 1, 2, 3, 4, 5 ]
83.333333
false
76.264591
6
1
16.666667
0
def plot_sphere(ax, x, y, z, size=1, color="k"): u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j] xl = x+size*np.cos(u)*np.sin(v) yl = y+size*np.sin(u)*np.sin(v) zl = z+size*np.cos(v) ax.plot_wireframe(xl, yl, zl, color=color)
1,504
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.calc_distance_and_angle
(from_node, to_node)
return d, phi, theta
304
311
def calc_distance_and_angle(from_node, to_node): dx = to_node.x[0] - from_node.x[0] dy = to_node.x[1] - from_node.x[1] dz = to_node.x[2] - from_node.x[2] d = np.sqrt(np.sum((np.array(to_node.x) - np.array(from_node.x))**2)) phi = math.atan2(dy, dx) theta = math.atan2(math.hypot(dx, dy), dz) return d, phi, theta
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L304-L311
2
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
76.264591
8
1
100
0
def calc_distance_and_angle(from_node, to_node): dx = to_node.x[0] - from_node.x[0] dy = to_node.x[1] - from_node.x[1] dz = to_node.x[2] - from_node.x[2] d = np.sqrt(np.sum((np.array(to_node.x) - np.array(from_node.x))**2)) phi = math.atan2(dy, dx) theta = math.atan2(math.hypot(dx, dy), dz) return d, phi, theta
1,505
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.calc_distance_and_angle2
(from_node, to_node)
return d, phi, theta
314
321
def calc_distance_and_angle2(from_node, to_node): dx = to_node.x[0] - from_node.x[0] dy = to_node.x[1] - from_node.x[1] dz = to_node.x[2] - from_node.x[2] d = math.sqrt(dx**2 + dy**2 + dz**2) phi = math.atan2(dy, dx) theta = math.atan2(math.hypot(dx, dy), dz) return d, phi, theta
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L314-L321
2
[ 0 ]
12.5
[ 1, 2, 3, 4, 5, 6, 7 ]
87.5
false
76.264591
8
1
12.5
0
def calc_distance_and_angle2(from_node, to_node): dx = to_node.x[0] - from_node.x[0] dy = to_node.x[1] - from_node.x[1] dz = to_node.x[2] - from_node.x[2] d = math.sqrt(dx**2 + dy**2 + dz**2) phi = math.atan2(dy, dx) theta = math.atan2(math.hypot(dx, dy), dz) return d, phi, theta
1,506
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py
RRTStar.check_collision
(node, robot, obstacleList)
return True
324
343
def check_collision(node, robot, obstacleList): if node is None: return False for (ox, oy, oz, size) in obstacleList: for x in node.path_x: x_list, y_list, z_list = robot.get_points(x) dx_list = [ox - x_point for x_point in x_list] dy_list = [oy - y_point for y_point in y_list] dz_list = [oz - z_point for z_point in z_list] d_list = [dx * dx + dy * dy + dz * dz for (dx, dy, dz) in zip(dx_list, dy_list, dz_list)] if min(d_list) <= size ** 2: return False # collision return True
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py#L324-L343
2
[ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 18, 19 ]
80
[ 3 ]
5
false
76.264591
20
9
95
0
def check_collision(node, robot, obstacleList): if node is None: return False for (ox, oy, oz, size) in obstacleList: for x in node.path_x: x_list, y_list, z_list = robot.get_points(x) dx_list = [ox - x_point for x_point in x_list] dy_list = [oy - y_point for y_point in y_list] dz_list = [oz - z_point for z_point in z_list] d_list = [dx * dx + dy * dy + dz * dz for (dx, dy, dz) in zip(dx_list, dy_list, dz_list)] if min(d_list) <= size ** 2: return False # collision return True
1,507
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Bipedal/bipedal_planner/bipedal_planner.py
BipedalPlanner.__init__
(self)
14
19
def __init__(self): self.act_p = [] # actual footstep positions self.ref_p = [] # reference footstep positions self.com_trajectory = [] self.ref_footsteps = None self.g = 9.8
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Bipedal/bipedal_planner/bipedal_planner.py#L14-L19
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
84.415584
6
1
100
0
def __init__(self): self.act_p = [] # actual footstep positions self.ref_p = [] # reference footstep positions self.com_trajectory = [] self.ref_footsteps = None self.g = 9.8
1,508
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Bipedal/bipedal_planner/bipedal_planner.py
BipedalPlanner.set_ref_footsteps
(self, ref_footsteps)
21
22
def set_ref_footsteps(self, ref_footsteps): self.ref_footsteps = ref_footsteps
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Bipedal/bipedal_planner/bipedal_planner.py#L21-L22
2
[ 0, 1 ]
100
[]
0
true
84.415584
2
1
100
0
def set_ref_footsteps(self, ref_footsteps): self.ref_footsteps = ref_footsteps
1,509
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Bipedal/bipedal_planner/bipedal_planner.py
BipedalPlanner.inverted_pendulum
(self, x, x_dot, px_star, y, y_dot, py_star, z_c, time_width)
return x, x_dot, y, y_dot
24
42
def inverted_pendulum(self, x, x_dot, px_star, y, y_dot, py_star, z_c, time_width): time_split = 100 for i in range(time_split): delta_time = time_width / time_split x_dot2 = self.g / z_c * (x - px_star) x += x_dot * delta_time x_dot += x_dot2 * delta_time y_dot2 = self.g / z_c * (y - py_star) y += y_dot * delta_time y_dot += y_dot2 * delta_time if i % 10 == 0: self.com_trajectory.append([x, y]) return x, x_dot, y, y_dot
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Bipedal/bipedal_planner/bipedal_planner.py#L24-L42
2
[ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
94.736842
[]
0
false
84.415584
19
3
100
0
def inverted_pendulum(self, x, x_dot, px_star, y, y_dot, py_star, z_c, time_width): time_split = 100 for i in range(time_split): delta_time = time_width / time_split x_dot2 = self.g / z_c * (x - px_star) x += x_dot * delta_time x_dot += x_dot2 * delta_time y_dot2 = self.g / z_c * (y - py_star) y += y_dot * delta_time y_dot += y_dot2 * delta_time if i % 10 == 0: self.com_trajectory.append([x, y]) return x, x_dot, y, y_dot
1,510
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Bipedal/bipedal_planner/bipedal_planner.py
BipedalPlanner.walk
(self, t_sup=0.8, z_c=0.8, a=10, b=1, plot=False)
44
117
def walk(self, t_sup=0.8, z_c=0.8, a=10, b=1, plot=False): if self.ref_footsteps is None: print("No footsteps") return # set up plotter com_trajectory_for_plot, ax = None, None if plot: fig = plt.figure() ax = Axes3D(fig) fig.add_axes(ax) com_trajectory_for_plot = [] px, py = 0.0, 0.0 # reference footstep position px_star, py_star = px, py # modified footstep position xi, xi_dot, yi, yi_dot = 0.0, 0.0, 0.01, 0.0 time = 0.0 n = 0 self.ref_p.append([px, py, 0]) self.act_p.append([px, py, 0]) for i in range(len(self.ref_footsteps)): # simulate x, y and those of dot of inverted pendulum xi, xi_dot, yi, yi_dot = self.inverted_pendulum( xi, xi_dot, px_star, yi, yi_dot, py_star, z_c, t_sup) # update time time += t_sup n += 1 # calculate px, py, x_, y_, vx_, vy_ f_x, f_y, f_theta = self.ref_footsteps[n - 1] rotate_mat = np.array([[math.cos(f_theta), -math.sin(f_theta)], [math.sin(f_theta), math.cos(f_theta)]]) if n == len(self.ref_footsteps): f_x_next, f_y_next, f_theta_next = 0., 0., 0. else: f_x_next, f_y_next, f_theta_next = self.ref_footsteps[n] rotate_mat_next = np.array( [[math.cos(f_theta_next), -math.sin(f_theta_next)], [math.sin(f_theta_next), math.cos(f_theta_next)]]) Tc = math.sqrt(z_c / self.g) C = math.cosh(t_sup / Tc) S = math.sinh(t_sup / Tc) px, py = list(np.array([px, py]) + np.dot(rotate_mat, np.array([f_x, -1 * math.pow(-1, n) * f_y]) )) x_, y_ = list(np.dot(rotate_mat_next, np.array( [f_x_next / 2., math.pow(-1, n) * f_y_next / 2.]))) vx_, vy_ = list(np.dot(rotate_mat_next, np.array( [(1 + C) / (Tc * S) * x_, (C - 1) / (Tc * S) * y_]))) self.ref_p.append([px, py, f_theta]) # calculate reference COM xd, xd_dot = px + x_, vx_ yd, yd_dot = py + y_, vy_ # calculate modified footsteps D = a * math.pow(C - 1, 2) + b * math.pow(S / Tc, 2) px_star = -a * (C - 1) / D * (xd - C * xi - Tc * S * xi_dot) \ - b * S / (Tc * D) * (xd_dot - S / Tc * xi - C * xi_dot) py_star = -a * (C - 1) / D * (yd - C * yi - Tc * S * yi_dot) \ - b * S / (Tc * D) * (yd_dot - S / Tc * yi - C * yi_dot) self.act_p.append([px_star, py_star, f_theta]) # plot if plot: self.plot_animation(ax, com_trajectory_for_plot, px_star, py_star, z_c) if plot: plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Bipedal/bipedal_planner/bipedal_planner.py#L44-L117
2
[ 0, 1, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 37, 38, 41, 42, 43, 44, 45, 46, 50, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 66, 67, 68, 69, 72 ]
68.918919
[ 2, 3, 8, 9, 10, 11, 70, 73 ]
10.810811
false
84.415584
74
7
89.189189
0
def walk(self, t_sup=0.8, z_c=0.8, a=10, b=1, plot=False): if self.ref_footsteps is None: print("No footsteps") return # set up plotter com_trajectory_for_plot, ax = None, None if plot: fig = plt.figure() ax = Axes3D(fig) fig.add_axes(ax) com_trajectory_for_plot = [] px, py = 0.0, 0.0 # reference footstep position px_star, py_star = px, py # modified footstep position xi, xi_dot, yi, yi_dot = 0.0, 0.0, 0.01, 0.0 time = 0.0 n = 0 self.ref_p.append([px, py, 0]) self.act_p.append([px, py, 0]) for i in range(len(self.ref_footsteps)): # simulate x, y and those of dot of inverted pendulum xi, xi_dot, yi, yi_dot = self.inverted_pendulum( xi, xi_dot, px_star, yi, yi_dot, py_star, z_c, t_sup) # update time time += t_sup n += 1 # calculate px, py, x_, y_, vx_, vy_ f_x, f_y, f_theta = self.ref_footsteps[n - 1] rotate_mat = np.array([[math.cos(f_theta), -math.sin(f_theta)], [math.sin(f_theta), math.cos(f_theta)]]) if n == len(self.ref_footsteps): f_x_next, f_y_next, f_theta_next = 0., 0., 0. else: f_x_next, f_y_next, f_theta_next = self.ref_footsteps[n] rotate_mat_next = np.array( [[math.cos(f_theta_next), -math.sin(f_theta_next)], [math.sin(f_theta_next), math.cos(f_theta_next)]]) Tc = math.sqrt(z_c / self.g) C = math.cosh(t_sup / Tc) S = math.sinh(t_sup / Tc) px, py = list(np.array([px, py]) + np.dot(rotate_mat, np.array([f_x, -1 * math.pow(-1, n) * f_y]) )) x_, y_ = list(np.dot(rotate_mat_next, np.array( [f_x_next / 2., math.pow(-1, n) * f_y_next / 2.]))) vx_, vy_ = list(np.dot(rotate_mat_next, np.array( [(1 + C) / (Tc * S) * x_, (C - 1) / (Tc * S) * y_]))) self.ref_p.append([px, py, f_theta]) # calculate reference COM xd, xd_dot = px + x_, vx_ yd, yd_dot = py + y_, vy_ # calculate modified footsteps D = a * math.pow(C - 1, 2) + b * math.pow(S / Tc, 2) px_star = -a * (C - 1) / D * (xd - C * xi - Tc * S * xi_dot) \ - b * S / (Tc * D) * (xd_dot - S / Tc * xi - C * xi_dot) py_star = -a * (C - 1) / D * (yd - C * yi - Tc * S * yi_dot) \ - b * S / (Tc * D) * (yd_dot - S / Tc * yi - C * yi_dot) self.act_p.append([px_star, py_star, f_theta]) # plot if plot: self.plot_animation(ax, com_trajectory_for_plot, px_star, py_star, z_c) if plot: plt.show()
1,511
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Bipedal/bipedal_planner/bipedal_planner.py
BipedalPlanner.plot_animation
(self, ax, com_trajectory_for_plot, px_star, py_star, z_c)
119
194
def plot_animation(self, ax, com_trajectory_for_plot, px_star, py_star, z_c): # pragma: no cover # for plot trajectory, plot in for loop for c in range(len(self.com_trajectory)): if c > len(com_trajectory_for_plot): # set up plotter plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) ax.set_zlim(0, z_c * 2) ax.set_xlim(0, 1) ax.set_ylim(-0.5, 0.5) # update com_trajectory_for_plot com_trajectory_for_plot.append(self.com_trajectory[c]) # plot com ax.plot([p[0] for p in com_trajectory_for_plot], [p[1] for p in com_trajectory_for_plot], [ 0 for _ in com_trajectory_for_plot], color="red") # plot inverted pendulum ax.plot([px_star, com_trajectory_for_plot[-1][0]], [py_star, com_trajectory_for_plot[-1][1]], [0, z_c], color="green", linewidth=3) ax.scatter([com_trajectory_for_plot[-1][0]], [com_trajectory_for_plot[-1][1]], [z_c], color="green", s=300) # foot rectangle for self.ref_p foot_width = 0.06 foot_height = 0.04 for j in range(len(self.ref_p)): angle = self.ref_p[j][2] + \ math.atan2(foot_height, foot_width) - math.pi r = math.sqrt( math.pow(foot_width / 3., 2) + math.pow( foot_height / 2., 2)) rec = pat.Rectangle(xy=( self.ref_p[j][0] + r * math.cos(angle), self.ref_p[j][1] + r * math.sin(angle)), width=foot_width, height=foot_height, angle=self.ref_p[j][ 2] * 180 / math.pi, color="blue", fill=False, ls=":") ax.add_patch(rec) art3d.pathpatch_2d_to_3d(rec, z=0, zdir="z") # foot rectangle for self.act_p for j in range(len(self.act_p)): angle = self.act_p[j][2] + \ math.atan2(foot_height, foot_width) - math.pi r = math.sqrt( math.pow(foot_width / 3., 2) + math.pow( foot_height / 2., 2)) rec = pat.Rectangle(xy=( self.act_p[j][0] + r * math.cos(angle), self.act_p[j][1] + r * math.sin(angle)), width=foot_width, height=foot_height, angle=self.act_p[j][ 2] * 180 / math.pi, color="blue", fill=False) ax.add_patch(rec) art3d.pathpatch_2d_to_3d(rec, z=0, zdir="z") plt.draw() plt.pause(0.001)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Bipedal/bipedal_planner/bipedal_planner.py#L119-L194
2
[]
0
[]
0
false
84.415584
76
8
100
0
def plot_animation(self, ax, com_trajectory_for_plot, px_star, py_star, z_c): # pragma: no cover # for plot trajectory, plot in for loop for c in range(len(self.com_trajectory)): if c > len(com_trajectory_for_plot): # set up plotter plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) ax.set_zlim(0, z_c * 2) ax.set_xlim(0, 1) ax.set_ylim(-0.5, 0.5) # update com_trajectory_for_plot com_trajectory_for_plot.append(self.com_trajectory[c]) # plot com ax.plot([p[0] for p in com_trajectory_for_plot], [p[1] for p in com_trajectory_for_plot], [ 0 for _ in com_trajectory_for_plot], color="red") # plot inverted pendulum ax.plot([px_star, com_trajectory_for_plot[-1][0]], [py_star, com_trajectory_for_plot[-1][1]], [0, z_c], color="green", linewidth=3) ax.scatter([com_trajectory_for_plot[-1][0]], [com_trajectory_for_plot[-1][1]], [z_c], color="green", s=300) # foot rectangle for self.ref_p foot_width = 0.06 foot_height = 0.04 for j in range(len(self.ref_p)): angle = self.ref_p[j][2] + \ math.atan2(foot_height, foot_width) - math.pi r = math.sqrt( math.pow(foot_width / 3., 2) + math.pow( foot_height / 2., 2)) rec = pat.Rectangle(xy=( self.ref_p[j][0] + r * math.cos(angle), self.ref_p[j][1] + r * math.sin(angle)), width=foot_width, height=foot_height, angle=self.ref_p[j][ 2] * 180 / math.pi, color="blue", fill=False, ls=":") ax.add_patch(rec) art3d.pathpatch_2d_to_3d(rec, z=0, zdir="z") # foot rectangle for self.act_p for j in range(len(self.act_p)): angle = self.act_p[j][2] + \ math.atan2(foot_height, foot_width) - math.pi r = math.sqrt( math.pow(foot_width / 3., 2) + math.pow( foot_height / 2., 2)) rec = pat.Rectangle(xy=( self.act_p[j][0] + r * math.cos(angle), self.act_p[j][1] + r * math.sin(angle)), width=foot_width, height=foot_height, angle=self.act_p[j][ 2] * 180 / math.pi, color="blue", fill=False) ax.add_patch(rec) art3d.pathpatch_2d_to_3d(rec, z=0, zdir="z") plt.draw() plt.pause(0.001)
1,512
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/parsers.py
BaseParser.parse
(self, stream, media_type, **options)
15
17
def parse(self, stream, media_type, **options): msg = '`parse()` method must be implemented for class "%s"' raise NotImplementedError(msg % self.__class__.__name__)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/parsers.py#L15-L17
3
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
0
def parse(self, stream, media_type, **options): msg = '`parse()` method must be implemented for class "%s"' raise NotImplementedError(msg % self.__class__.__name__)
1,590
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/parsers.py
JSONParser.parse
(self, stream, media_type, **options)
23
29
def parse(self, stream, media_type, **options): data = stream.read().decode("utf-8") try: return json.loads(data) except ValueError as exc: msg = "JSON parse error - %s" % str(exc) raise exceptions.ParseError(msg)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/parsers.py#L23-L29
3
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
100
7
2
100
0
def parse(self, stream, media_type, **options): data = stream.read().decode("utf-8") try: return json.loads(data) except ValueError as exc: msg = "JSON parse error - %s" % str(exc) raise exceptions.ParseError(msg)
1,591
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/parsers.py
MultiPartParser.parse
(self, stream, media_type, **options)
37
60
def parse(self, stream, media_type, **options): boundary = media_type.params.get("boundary") if boundary is None: msg = "Multipart message missing boundary in Content-Type header" raise exceptions.ParseError(msg) boundary = boundary.encode("ascii") content_length = options.get("content_length") assert ( content_length is not None ), "MultiPartParser.parse() requires `content_length` argument" buffer_size = content_length while buffer_size % 4 or buffer_size < 1024: buffer_size += 1 multipart_parser = WerkzeugMultiPartParser( default_stream_factory, buffer_size=buffer_size ) try: return multipart_parser.parse(stream, boundary, content_length) except ValueError as exc: msg = "Multipart parse error - %s" % str(exc) raise exceptions.ParseError(msg)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/parsers.py#L37-L60
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22, 23 ]
83.333333
[]
0
false
100
24
6
100
0
def parse(self, stream, media_type, **options): boundary = media_type.params.get("boundary") if boundary is None: msg = "Multipart message missing boundary in Content-Type header" raise exceptions.ParseError(msg) boundary = boundary.encode("ascii") content_length = options.get("content_length") assert ( content_length is not None ), "MultiPartParser.parse() requires `content_length` argument" buffer_size = content_length while buffer_size % 4 or buffer_size < 1024: buffer_size += 1 multipart_parser = WerkzeugMultiPartParser( default_stream_factory, buffer_size=buffer_size ) try: return multipart_parser.parse(stream, boundary, content_length) except ValueError as exc: msg = "Multipart parse error - %s" % str(exc) raise exceptions.ParseError(msg)
1,592
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/parsers.py
URLEncodedParser.parse
(self, stream, media_type, **options)
return url_decode_stream(stream)
67
68
def parse(self, stream, media_type, **options): return url_decode_stream(stream)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/parsers.py#L67-L68
3
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def parse(self, stream, media_type, **options): return url_decode_stream(stream)
1,593
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/negotiation.py
BaseNegotiation.select_parser
(self, parsers)
8
10
def select_parser(self, parsers): msg = '`select_parser()` method must be implemented for class "%s"' raise NotImplementedError(msg % self.__class__.__name__)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/negotiation.py#L8-L10
3
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
0
def select_parser(self, parsers): msg = '`select_parser()` method must be implemented for class "%s"' raise NotImplementedError(msg % self.__class__.__name__)
1,594
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/negotiation.py
BaseNegotiation.select_renderer
(self, renderers)
12
14
def select_renderer(self, renderers): msg = '`select_renderer()` method must be implemented for class "%s"' raise NotImplementedError(msg % self.__class__.__name__)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/negotiation.py#L12-L14
3
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
0
def select_renderer(self, renderers): msg = '`select_renderer()` method must be implemented for class "%s"' raise NotImplementedError(msg % self.__class__.__name__)
1,595
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/negotiation.py
DefaultNegotiation.select_parser
(self, parsers)
Determine which parser to use for parsing the request body. Returns a two-tuple of (parser, content type).
Determine which parser to use for parsing the request body. Returns a two-tuple of (parser, content type).
18
31
def select_parser(self, parsers): """ Determine which parser to use for parsing the request body. Returns a two-tuple of (parser, content type). """ content_type_header = request.content_type client_media_type = MediaType(content_type_header) for parser in parsers: server_media_type = MediaType(parser.media_type) if server_media_type.satisfies(client_media_type): return (parser, client_media_type) raise exceptions.UnsupportedMediaType()
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/negotiation.py#L18-L31
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
100
14
3
100
2
def select_parser(self, parsers): content_type_header = request.content_type client_media_type = MediaType(content_type_header) for parser in parsers: server_media_type = MediaType(parser.media_type) if server_media_type.satisfies(client_media_type): return (parser, client_media_type) raise exceptions.UnsupportedMediaType()
1,596
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/negotiation.py
DefaultNegotiation.select_renderer
(self, renderers)
Determine which renderer to use for rendering the response body. Returns a two-tuple of (renderer, content type).
Determine which renderer to use for rendering the response body. Returns a two-tuple of (renderer, content type).
33
50
def select_renderer(self, renderers): """ Determine which renderer to use for rendering the response body. Returns a two-tuple of (renderer, content type). """ accept_header = request.headers.get("Accept", "*/*") for client_media_types in parse_accept_header(accept_header): for renderer in renderers: server_media_type = MediaType(renderer.media_type) for client_media_type in client_media_types: if client_media_type.satisfies(server_media_type): if server_media_type.precedence > client_media_type.precedence: return (renderer, server_media_type) else: return (renderer, client_media_type) raise exceptions.NotAcceptable()
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/negotiation.py#L33-L50
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
100
18
6
100
2
def select_renderer(self, renderers): accept_header = request.headers.get("Accept", "*/*") for client_media_types in parse_accept_header(accept_header): for renderer in renderers: server_media_type = MediaType(renderer.media_type) for client_media_type in client_media_types: if client_media_type.satisfies(server_media_type): if server_media_type.precedence > client_media_type.precedence: return (renderer, server_media_type) else: return (renderer, client_media_type) raise exceptions.NotAcceptable()
1,597
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/app.py
urlize_quoted_links
(content)
return re.sub(r'"(https?://[^"]*)"', r'"<a href="\1">\1</a>"', content)
24
25
def urlize_quoted_links(content): return re.sub(r'"(https?://[^"]*)"', r'"<a href="\1">\1</a>"', content)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/app.py#L24-L25
3
[ 0, 1 ]
100
[]
0
true
88.75
2
1
100
0
def urlize_quoted_links(content): return re.sub(r'"(https?://[^"]*)"', r'"<a href="\1">\1</a>"', content)
1,598
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/app.py
FlaskAPI.__init__
(self, *args, **kwargs)
32
36
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.api_settings = APISettings(self.config) self.register_blueprint(api_resources) self.jinja_env.filters["urlize_quoted_links"] = urlize_quoted_links
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/app.py#L32-L36
3
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
88.75
5
1
100
0
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.api_settings = APISettings(self.config) self.register_blueprint(api_resources) self.jinja_env.filters["urlize_quoted_links"] = urlize_quoted_links
1,599
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/app.py
FlaskAPI.preprocess_request
(self)
return super().preprocess_request()
38
41
def preprocess_request(self): request.parser_classes = self.api_settings.DEFAULT_PARSERS request.renderer_classes = self.api_settings.DEFAULT_RENDERERS return super().preprocess_request()
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/app.py#L38-L41
3
[ 0, 1, 2, 3 ]
100
[]
0
true
88.75
4
1
100
0
def preprocess_request(self): request.parser_classes = self.api_settings.DEFAULT_PARSERS request.renderer_classes = self.api_settings.DEFAULT_RENDERERS return super().preprocess_request()
1,600
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/app.py
FlaskAPI.make_response
(self, rv)
return rv
We override this so that we can additionally handle list and dict types by default.
We override this so that we can additionally handle list and dict types by default.
43
77
def make_response(self, rv): """ We override this so that we can additionally handle list and dict types by default. """ status_or_headers = headers = None if isinstance(rv, tuple): rv, status_or_headers, headers = rv + (None,) * (3 - len(rv)) if rv is None and status_or_headers == HTTP_204_NO_CONTENT: rv = "" if rv is None and status_or_headers: raise ValueError("View function did not return a response") if isinstance(status_or_headers, (dict, list)): headers, status_or_headers = status_or_headers, None if not isinstance(rv, self.response_class): if isinstance(rv, (str, bytes, bytearray, list, dict)): status = status_or_headers rv = self.response_class(rv, headers=headers, status=status) headers = status_or_headers = None else: rv = self.response_class.force_type(rv, request.environ) if status_or_headers is not None: if isinstance(status_or_headers, str): rv.status = status_or_headers else: rv.status_code = status_or_headers if headers: rv.headers.extend(headers) return rv
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/app.py#L43-L77
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 31, 33, 34 ]
85.714286
[ 27, 28, 30, 32 ]
11.428571
false
88.75
35
12
88.571429
2
def make_response(self, rv): status_or_headers = headers = None if isinstance(rv, tuple): rv, status_or_headers, headers = rv + (None,) * (3 - len(rv)) if rv is None and status_or_headers == HTTP_204_NO_CONTENT: rv = "" if rv is None and status_or_headers: raise ValueError("View function did not return a response") if isinstance(status_or_headers, (dict, list)): headers, status_or_headers = status_or_headers, None if not isinstance(rv, self.response_class): if isinstance(rv, (str, bytes, bytearray, list, dict)): status = status_or_headers rv = self.response_class(rv, headers=headers, status=status) headers = status_or_headers = None else: rv = self.response_class.force_type(rv, request.environ) if status_or_headers is not None: if isinstance(status_or_headers, str): rv.status = status_or_headers else: rv.status_code = status_or_headers if headers: rv.headers.extend(headers) return rv
1,601
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/app.py
FlaskAPI.handle_user_exception
(self, e)
We override the default behavior in order to deal with APIException.
We override the default behavior in order to deal with APIException.
79
108
def handle_user_exception(self, e): """ We override the default behavior in order to deal with APIException. """ exc_type, exc_value, tb = sys.exc_info() assert exc_value is e if isinstance(e, HTTPException) and not self.trap_http_exception(e): return self.handle_http_exception(e) if isinstance(e, APIException): return self.handle_api_exception(e) blueprint_handlers = () handlers = self.error_handler_spec.get(request.blueprint) if handlers is not None: blueprint_handlers = handlers.get(None, ()) app_handlers = self.error_handler_spec[None].get(None, ()) if is_flask_legacy(): for typecheck, handler in chain(blueprint_handlers, app_handlers): if isinstance(e, typecheck): return handler(e) else: for typecheck, handler in chain( dict(blueprint_handlers).items(), dict(app_handlers).items() ): if isinstance(e, typecheck): return handler(e) raise e
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/app.py#L79-L108
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 22, 23, 24, 25, 26, 27, 28 ]
86.666667
[ 19, 20, 21, 29 ]
13.333333
false
88.75
30
11
86.666667
1
def handle_user_exception(self, e): exc_type, exc_value, tb = sys.exc_info() assert exc_value is e if isinstance(e, HTTPException) and not self.trap_http_exception(e): return self.handle_http_exception(e) if isinstance(e, APIException): return self.handle_api_exception(e) blueprint_handlers = () handlers = self.error_handler_spec.get(request.blueprint) if handlers is not None: blueprint_handlers = handlers.get(None, ()) app_handlers = self.error_handler_spec[None].get(None, ()) if is_flask_legacy(): for typecheck, handler in chain(blueprint_handlers, app_handlers): if isinstance(e, typecheck): return handler(e) else: for typecheck, handler in chain( dict(blueprint_handlers).items(), dict(app_handlers).items() ): if isinstance(e, typecheck): return handler(e) raise e
1,602
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/app.py
FlaskAPI.handle_api_exception
(self, exc)
return self.response_class(content, status=status)
110
113
def handle_api_exception(self, exc): content = {"message": exc.detail} status = exc.status_code return self.response_class(content, status=status)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/app.py#L110-L113
3
[ 0, 1, 2, 3 ]
100
[]
0
true
88.75
4
1
100
0
def handle_api_exception(self, exc): content = {"message": exc.detail} status = exc.status_code return self.response_class(content, status=status)
1,603
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/app.py
FlaskAPI.create_url_adapter
(self, request)
We need to override the default behavior slightly here, to ensure the any method-based routing takes account of any method overloading, so that eg PUT requests from the browsable API are routed to the correct view.
We need to override the default behavior slightly here, to ensure the any method-based routing takes account of any method overloading, so that eg PUT requests from the browsable API are routed to the correct view.
115
135
def create_url_adapter(self, request): """ We need to override the default behavior slightly here, to ensure the any method-based routing takes account of any method overloading, so that eg PUT requests from the browsable API are routed to the correct view. """ if request is not None: environ = request.environ.copy() environ["REQUEST_METHOD"] = request.method return self.url_map.bind_to_environ( environ, server_name=self.config["SERVER_NAME"] ) # We need at the very least the server name to be set for this # to work. if self.config["SERVER_NAME"] is not None: return self.url_map.bind( self.config["SERVER_NAME"], script_name=self.config["APPLICATION_ROOT"] or "/", url_scheme=self.config["PREFERRED_URL_SCHEME"], )
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/app.py#L115-L135
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
76.190476
[ 16 ]
4.761905
false
88.75
21
4
95.238095
4
def create_url_adapter(self, request): if request is not None: environ = request.environ.copy() environ["REQUEST_METHOD"] = request.method return self.url_map.bind_to_environ( environ, server_name=self.config["SERVER_NAME"] ) # We need at the very least the server name to be set for this # to work. if self.config["SERVER_NAME"] is not None: return self.url_map.bind( self.config["SERVER_NAME"], script_name=self.config["APPLICATION_ROOT"] or "/", url_scheme=self.config["PREFERRED_URL_SCHEME"], )
1,604
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/exceptions.py
APIException.__init__
(self, detail=None)
8
10
def __init__(self, detail=None): if detail is not None: self.detail = detail
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/exceptions.py#L8-L10
3
[ 0, 1, 2 ]
100
[]
0
true
100
3
2
100
0
def __init__(self, detail=None): if detail is not None: self.detail = detail
1,605
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/exceptions.py
APIException.__str__
(self)
return self.detail
12
13
def __str__(self): return self.detail
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/exceptions.py#L12-L13
3
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def __str__(self): return self.detail
1,606
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/response.py
APIResponse.__init__
(self, content=None, *args, **kwargs)
8
30
def __init__(self, content=None, *args, **kwargs): super().__init__(None, *args, **kwargs) media_type = None if isinstance(content, self.api_return_types) or content == "": renderer = request.accepted_renderer if content != "" or renderer.handles_empty_responses: media_type = request.accepted_media_type options = self.get_renderer_options() content = renderer.render(content, media_type, **options) if self.status_code == 204: self.status_code = 200 # From `werkzeug.wrappers.BaseResponse` if content is None: content = [] if isinstance(content, (str, bytes, bytearray)): self.set_data(content) else: self.response = content if media_type is not None: self.headers["Content-Type"] = str(media_type)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/response.py#L8-L30
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 19, 20, 21, 22 ]
86.956522
[ 11 ]
4.347826
false
95.652174
23
9
95.652174
0
def __init__(self, content=None, *args, **kwargs): super().__init__(None, *args, **kwargs) media_type = None if isinstance(content, self.api_return_types) or content == "": renderer = request.accepted_renderer if content != "" or renderer.handles_empty_responses: media_type = request.accepted_media_type options = self.get_renderer_options() content = renderer.render(content, media_type, **options) if self.status_code == 204: self.status_code = 200 # From `werkzeug.wrappers.BaseResponse` if content is None: content = [] if isinstance(content, (str, bytes, bytearray)): self.set_data(content) else: self.response = content if media_type is not None: self.headers["Content-Type"] = str(media_type)
1,607
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/response.py
APIResponse.get_renderer_options
(self)
return { "status": self.status, "status_code": self.status_code, "headers": self.headers, }
32
37
def get_renderer_options(self): return { "status": self.status, "status_code": self.status_code, "headers": self.headers, }
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/response.py#L32-L37
3
[ 0, 1 ]
33.333333
[]
0
false
95.652174
6
1
100
0
def get_renderer_options(self): return { "status": self.status, "status_code": self.status_code, "headers": self.headers, }
1,608
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/renderers.py
dedent
(content)
return content.strip()
Remove leading indent from a block of text. Used when generating descriptions from docstrings. Note that python's `textwrap.dedent` doesn't quite cut it, as it fails to dedent multiline docstrings that include unindented text on the initial line.
Remove leading indent from a block of text. Used when generating descriptions from docstrings.
12
32
def dedent(content): """ Remove leading indent from a block of text. Used when generating descriptions from docstrings. Note that python's `textwrap.dedent` doesn't quite cut it, as it fails to dedent multiline docstrings that include unindented text on the initial line. """ whitespace_counts = [ len(line) - len(line.lstrip(" ")) for line in content.splitlines()[1:] if line.lstrip() ] # unindent the content if needed if whitespace_counts: whitespace_pattern = "^" + (" " * min(whitespace_counts)) content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), "", content) return content.strip()
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/renderers.py#L12-L32
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
42.857143
[ 9, 16, 17, 18, 20 ]
23.809524
false
86.30137
21
3
76.190476
6
def dedent(content): whitespace_counts = [ len(line) - len(line.lstrip(" ")) for line in content.splitlines()[1:] if line.lstrip() ] # unindent the content if needed if whitespace_counts: whitespace_pattern = "^" + (" " * min(whitespace_counts)) content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), "", content) return content.strip()
1,609
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/renderers.py
convert_to_title
(name)
return name.capitalize()
35
38
def convert_to_title(name): for char in ["-", "_", "."]: name = name.replace(char, " ") return name.capitalize()
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/renderers.py#L35-L38
3
[ 0, 1, 2, 3 ]
100
[]
0
true
86.30137
4
2
100
0
def convert_to_title(name): for char in ["-", "_", "."]: name = name.replace(char, " ") return name.capitalize()
1,610
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/renderers.py
BaseRenderer.render
(self, data, media_type, **options)
46
48
def render(self, data, media_type, **options): msg = '`render()` method must be implemented for class "%s"' raise NotImplementedError(msg % self.__class__.__name__)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/renderers.py#L46-L48
3
[ 0, 1, 2 ]
100
[]
0
true
86.30137
3
1
100
0
def render(self, data, media_type, **options): msg = '`render()` method must be implemented for class "%s"' raise NotImplementedError(msg % self.__class__.__name__)
1,611
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/renderers.py
JSONRenderer.render
(self, data, media_type, **options)
return json.dumps( data, cls=current_app.json_encoder, ensure_ascii=False, indent=indent )
55
65
def render(self, data, media_type, **options): # Requested indentation may be set in the Accept header. try: indent = max(min(int(media_type.params["indent"]), 8), 0) except (KeyError, ValueError, TypeError): indent = None # Indent may be set explicitly, eg when rendered by the browsable API. indent = options.get("indent", indent) return json.dumps( data, cls=current_app.json_encoder, ensure_ascii=False, indent=indent )
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/renderers.py#L55-L65
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
81.818182
[]
0
false
86.30137
11
2
100
0
def render(self, data, media_type, **options): # Requested indentation may be set in the Accept header. try: indent = max(min(int(media_type.params["indent"]), 8), 0) except (KeyError, ValueError, TypeError): indent = None # Indent may be set explicitly, eg when rendered by the browsable API. indent = options.get("indent", indent) return json.dumps( data, cls=current_app.json_encoder, ensure_ascii=False, indent=indent )
1,612
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/renderers.py
HTMLRenderer.render
(self, data, media_type, **options)
return data.encode(self.charset)
72
73
def render(self, data, media_type, **options): return data.encode(self.charset)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/renderers.py#L72-L73
3
[ 0 ]
50
[ 1 ]
50
false
86.30137
2
1
50
0
def render(self, data, media_type, **options): return data.encode(self.charset)
1,613
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/renderers.py
BrowsableAPIRenderer.render
(self, data, media_type, **options)
return render_template(self.template, **context)
81
128
def render(self, data, media_type, **options): # Render the content as it would have been if the client # had requested 'Accept: */*'. available_renderers = [ renderer for renderer in request.renderer_classes if not issubclass(renderer, BrowsableAPIRenderer) ] assert available_renderers, "BrowsableAPIRenderer cannot be the only renderer" mock_renderer = available_renderers[0]() mock_media_type = MediaType(mock_renderer.media_type) if data == "" and not mock_renderer.handles_empty_responses: mock_content = None else: text = mock_renderer.render(data, mock_media_type, indent=4) mock_content = self._html_escape(text) # Determine the allowed methods on this view. adapter = _request_ctx_stack.top.url_adapter allowed_methods = adapter.allowed_methods() endpoint = request.url_rule.endpoint view_name = str(endpoint) view_description = current_app.view_functions[endpoint].__doc__ if view_description: if apply_markdown: view_description = dedent(view_description) view_description = apply_markdown(view_description) else: # pragma: no cover - markdown installed for tests view_description = dedent(view_description) view_description = pydoc.html.preformat(view_description) status = options["status"] headers = options["headers"] headers["Content-Type"] = str(mock_media_type) from flask_api import __version__ context = { "status": status, "headers": headers, "content": mock_content, "allowed_methods": allowed_methods, "view_name": convert_to_title(view_name), "view_description": view_description, "version": __version__, } return render_template(self.template, **context)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/renderers.py#L81-L128
3
[ 0, 1, 2, 3, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 31, 32, 33, 34, 35, 36, 37, 38, 47 ]
62.222222
[ 12, 25, 26, 27 ]
8.888889
false
86.30137
48
7
91.111111
0
def render(self, data, media_type, **options): # Render the content as it would have been if the client # had requested 'Accept: */*'. available_renderers = [ renderer for renderer in request.renderer_classes if not issubclass(renderer, BrowsableAPIRenderer) ] assert available_renderers, "BrowsableAPIRenderer cannot be the only renderer" mock_renderer = available_renderers[0]() mock_media_type = MediaType(mock_renderer.media_type) if data == "" and not mock_renderer.handles_empty_responses: mock_content = None else: text = mock_renderer.render(data, mock_media_type, indent=4) mock_content = self._html_escape(text) # Determine the allowed methods on this view. adapter = _request_ctx_stack.top.url_adapter allowed_methods = adapter.allowed_methods() endpoint = request.url_rule.endpoint view_name = str(endpoint) view_description = current_app.view_functions[endpoint].__doc__ if view_description: if apply_markdown: view_description = dedent(view_description) view_description = apply_markdown(view_description) else: # pragma: no cover - markdown installed for tests view_description = dedent(view_description) view_description = pydoc.html.preformat(view_description) status = options["status"] headers = options["headers"] headers["Content-Type"] = str(mock_media_type) from flask_api import __version__ context = { "status": status, "headers": headers, "content": mock_content, "allowed_methods": allowed_methods, "view_name": convert_to_title(view_name), "view_description": view_description, "version": __version__, } return render_template(self.template, **context)
1,614
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/renderers.py
BrowsableAPIRenderer._html_escape
(text)
return text
131
137
def _html_escape(text): escape_table = [("&", "&amp;"), ("<", "&lt;"), (">", "&gt;")] for char, replacement in escape_table: text = text.replace(char, replacement) return text
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/renderers.py#L131-L137
3
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
86.30137
7
2
100
0
def _html_escape(text): escape_table = [("&", "&amp;"), ("<", "&lt;"), (">", "&gt;")] for char, replacement in escape_table: text = text.replace(char, replacement) return text
1,615
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/decorators.py
set_parsers
(*parsers)
return decorator
6
18
def set_parsers(*parsers): def decorator(func): @wraps(func) def decorated_function(*args, **kwargs): if len(parsers) == 1 and isinstance(parsers[0], (list, tuple)): request.parser_classes = parsers[0] else: request.parser_classes = parsers return func(*args, **kwargs) return decorated_function return decorator
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/decorators.py#L6-L18
3
[ 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12 ]
92.307692
[]
0
false
100
13
5
100
0
def set_parsers(*parsers): def decorator(func): @wraps(func) def decorated_function(*args, **kwargs): if len(parsers) == 1 and isinstance(parsers[0], (list, tuple)): request.parser_classes = parsers[0] else: request.parser_classes = parsers return func(*args, **kwargs) return decorated_function return decorator
1,616
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/decorators.py
set_renderers
(*renderers)
return decorator
21
33
def set_renderers(*renderers): def decorator(func): @wraps(func) def decorated_function(*args, **kwargs): if len(renderers) == 1 and isinstance(renderers[0], (list, tuple)): request.renderer_classes = renderers[0] else: request.renderer_classes = renderers return func(*args, **kwargs) return decorated_function return decorator
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/decorators.py#L21-L33
3
[ 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12 ]
92.307692
[]
0
false
100
13
5
100
0
def set_renderers(*renderers): def decorator(func): @wraps(func) def decorated_function(*args, **kwargs): if len(renderers) == 1 and isinstance(renderers[0], (list, tuple)): request.renderer_classes = renderers[0] else: request.renderer_classes = renderers return func(*args, **kwargs) return decorated_function return decorator
1,617
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/settings.py
perform_imports
(val, setting_name)
return val
If the given setting is a string import notation, then perform the necessary import or imports.
If the given setting is a string import notation, then perform the necessary import or imports.
4
13
def perform_imports(val, setting_name): """ If the given setting is a string import notation, then perform the necessary import or imports. """ if isinstance(val, str): return import_from_string(val, setting_name) elif isinstance(val, (list, tuple)): return [perform_imports(item, setting_name) for item in val] return val
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/settings.py#L4-L13
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
100
10
4
100
2
def perform_imports(val, setting_name): if isinstance(val, str): return import_from_string(val, setting_name) elif isinstance(val, (list, tuple)): return [perform_imports(item, setting_name) for item in val] return val
1,618
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/settings.py
import_from_string
(val, setting_name)
Attempt to import a class from a string representation.
Attempt to import a class from a string representation.
16
29
def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: # Nod to tastypie's use of importlib. parts = val.split(".") module_path, class_name = ".".join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr(module, class_name) except ImportError as exc: format = "Could not import '%s' for API setting '%s'. %s." msg = format % (val, setting_name, exc) raise ImportError(msg)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/settings.py#L16-L29
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
100
14
2
100
1
def import_from_string(val, setting_name): try: # Nod to tastypie's use of importlib. parts = val.split(".") module_path, class_name = ".".join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr(module, class_name) except ImportError as exc: format = "Could not import '%s' for API setting '%s'. %s." msg = format % (val, setting_name, exc) raise ImportError(msg)
1,619
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/settings.py
APISettings.__init__
(self, user_config=None)
33
34
def __init__(self, user_config=None): self.user_config = user_config or {}
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/settings.py#L33-L34
3
[ 0, 1 ]
100
[]
0
true
100
2
2
100
0
def __init__(self, user_config=None): self.user_config = user_config or {}
1,620
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/settings.py
APISettings.DEFAULT_PARSERS
(self)
return perform_imports(val, "DEFAULT_PARSERS")
37
44
def DEFAULT_PARSERS(self): default = [ "flask_api.parsers.JSONParser", "flask_api.parsers.URLEncodedParser", "flask_api.parsers.MultiPartParser", ] val = self.user_config.get("DEFAULT_PARSERS", default) return perform_imports(val, "DEFAULT_PARSERS")
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/settings.py#L37-L44
3
[ 0, 1, 6, 7 ]
50
[]
0
false
100
8
1
100
0
def DEFAULT_PARSERS(self): default = [ "flask_api.parsers.JSONParser", "flask_api.parsers.URLEncodedParser", "flask_api.parsers.MultiPartParser", ] val = self.user_config.get("DEFAULT_PARSERS", default) return perform_imports(val, "DEFAULT_PARSERS")
1,621
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/settings.py
APISettings.DEFAULT_RENDERERS
(self)
return perform_imports(val, "DEFAULT_RENDERERS")
47
53
def DEFAULT_RENDERERS(self): default = [ "flask_api.renderers.JSONRenderer", "flask_api.renderers.BrowsableAPIRenderer", ] val = self.user_config.get("DEFAULT_RENDERERS", default) return perform_imports(val, "DEFAULT_RENDERERS")
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/settings.py#L47-L53
3
[ 0, 1, 5, 6 ]
57.142857
[]
0
false
100
7
1
100
0
def DEFAULT_RENDERERS(self): default = [ "flask_api.renderers.JSONRenderer", "flask_api.renderers.BrowsableAPIRenderer", ] val = self.user_config.get("DEFAULT_RENDERERS", default) return perform_imports(val, "DEFAULT_RENDERERS")
1,622
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.data
(self)
return self._data
21
24
def data(self): if not hasattr(self, "_data"): self._parse() return self._data
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L21-L24
3
[ 0, 1, 2, 3 ]
100
[]
0
true
90.990991
4
2
100
0
def data(self): if not hasattr(self, "_data"): self._parse() return self._data
1,623
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.form
(self)
return self._form
27
30
def form(self): if not hasattr(self, "_form"): self._parse() return self._form
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L27-L30
3
[ 0, 1, 2, 3 ]
100
[]
0
true
90.990991
4
2
100
0
def form(self): if not hasattr(self, "_form"): self._parse() return self._form
1,624
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.files
(self)
return self._files
33
36
def files(self): if not hasattr(self, "_files"): self._parse() return self._files
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L33-L36
3
[ 0, 1, 2, 3 ]
100
[]
0
true
90.990991
4
2
100
0
def files(self): if not hasattr(self, "_files"): self._parse() return self._files
1,625
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest._parse
(self)
Parse the body of the request, using whichever parser satisfies the client 'Content-Type' header.
Parse the body of the request, using whichever parser satisfies the client 'Content-Type' header.
38
68
def _parse(self): """ Parse the body of the request, using whichever parser satisfies the client 'Content-Type' header. """ if not self.content_type or not self.content_length: self._set_empty_data() return negotiator = self.negotiator_class() parsers = [parser_cls() for parser_cls in self.parser_classes] options = self._get_parser_options() try: parser, media_type = negotiator.select_parser(parsers) ret = parser.parse(self.stream, media_type, **options) except Exception as e: # Ensure that accessing `request.data` again does not reraise # the exception, so that eg exceptions can handle properly. self._set_empty_data() raise e from None if parser.handles_file_uploads: assert ( isinstance(ret, tuple) and len(ret) == 2 ), "Expected a two-tuple of (data, files)" self._data, self._files = ret else: self._data = ret self._files = self.empty_data_class() self._form = self._data if parser.handles_form_data else self.empty_data_class()
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L38-L68
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ]
100
[]
0
true
90.990991
31
8
100
2
def _parse(self): if not self.content_type or not self.content_length: self._set_empty_data() return negotiator = self.negotiator_class() parsers = [parser_cls() for parser_cls in self.parser_classes] options = self._get_parser_options() try: parser, media_type = negotiator.select_parser(parsers) ret = parser.parse(self.stream, media_type, **options) except Exception as e: # Ensure that accessing `request.data` again does not reraise # the exception, so that eg exceptions can handle properly. self._set_empty_data() raise e from None if parser.handles_file_uploads: assert ( isinstance(ret, tuple) and len(ret) == 2 ), "Expected a two-tuple of (data, files)" self._data, self._files = ret else: self._data = ret self._files = self.empty_data_class() self._form = self._data if parser.handles_form_data else self.empty_data_class()
1,626
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest._get_parser_options
(self)
return {"content_length": self.content_length}
Any additional information to pass to the parser.
Any additional information to pass to the parser.
70
74
def _get_parser_options(self): """ Any additional information to pass to the parser. """ return {"content_length": self.content_length}
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L70-L74
3
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
90.990991
5
1
100
1
def _get_parser_options(self): return {"content_length": self.content_length}
1,627
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest._set_empty_data
(self)
If the request does not contain data then return an empty representation.
If the request does not contain data then return an empty representation.
76
82
def _set_empty_data(self): """ If the request does not contain data then return an empty representation. """ self._data = self.empty_data_class() self._form = self.empty_data_class() self._files = self.empty_data_class()
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L76-L82
3
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
90.990991
7
1
100
1
def _set_empty_data(self): self._data = self.empty_data_class() self._form = self.empty_data_class() self._files = self.empty_data_class()
1,628
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.accepted_renderer
(self)
return self._accepted_renderer
87
90
def accepted_renderer(self): if not hasattr(self, "_accepted_renderer"): self._perform_content_negotiation() return self._accepted_renderer
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L87-L90
3
[ 0, 1, 2, 3 ]
100
[]
0
true
90.990991
4
2
100
0
def accepted_renderer(self): if not hasattr(self, "_accepted_renderer"): self._perform_content_negotiation() return self._accepted_renderer
1,629
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.accepted_media_type
(self)
return self._accepted_media_type
93
96
def accepted_media_type(self): if not hasattr(self, "_accepted_media_type"): self._perform_content_negotiation() return self._accepted_media_type
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L93-L96
3
[ 0, 1, 2, 3 ]
100
[]
0
true
90.990991
4
2
100
0
def accepted_media_type(self): if not hasattr(self, "_accepted_media_type"): self._perform_content_negotiation() return self._accepted_media_type
1,630
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest._perform_content_negotiation
(self)
Determine which of the available renderers should be used for rendering the response content, based on the client 'Accept' header.
Determine which of the available renderers should be used for rendering the response content, based on the client 'Accept' header.
98
107
def _perform_content_negotiation(self): """ Determine which of the available renderers should be used for rendering the response content, based on the client 'Accept' header. """ negotiator = self.negotiator_class() renderers = [renderer() for renderer in self.renderer_classes] self._accepted_renderer, self._accepted_media_type = negotiator.select_renderer( renderers )
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L98-L107
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
90.990991
10
2
100
2
def _perform_content_negotiation(self): negotiator = self.negotiator_class() renderers = [renderer() for renderer in self.renderer_classes] self._accepted_renderer, self._accepted_media_type = negotiator.select_renderer( renderers )
1,631
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.method
(self)
return self._method
112
115
def method(self): if not hasattr(self, "_method"): self._perform_method_overloading() return self._method
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L112-L115
3
[ 0, 1, 3 ]
75
[ 2 ]
25
false
90.990991
4
2
75
0
def method(self): if not hasattr(self, "_method"): self._perform_method_overloading() return self._method
1,632
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.method
(self, value)
118
119
def method(self, value): self._method = value
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L118-L119
3
[ 0, 1 ]
100
[]
0
true
90.990991
2
1
100
0
def method(self, value): self._method = value
1,633
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.content_type
(self)
return self._content_type
122
125
def content_type(self): if not hasattr(self, "_content_type"): self._perform_method_overloading() return self._content_type
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L122-L125
3
[ 0, 1, 2, 3 ]
100
[]
0
true
90.990991
4
2
100
0
def content_type(self): if not hasattr(self, "_content_type"): self._perform_method_overloading() return self._content_type
1,634
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.content_length
(self)
return self._content_length
128
131
def content_length(self): if not hasattr(self, "_content_length"): self._perform_method_overloading() return self._content_length
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L128-L131
3
[ 0, 1, 3 ]
75
[ 2 ]
25
false
90.990991
4
2
75
0
def content_length(self): if not hasattr(self, "_content_length"): self._perform_method_overloading() return self._content_length
1,635
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.stream
(self)
return self._stream
134
137
def stream(self): if not hasattr(self, "_stream"): self._perform_method_overloading() return self._stream
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L134-L137
3
[ 0, 1, 3 ]
75
[ 2 ]
25
false
90.990991
4
2
75
0
def stream(self): if not hasattr(self, "_stream"): self._perform_method_overloading() return self._stream
1,636
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest._perform_method_overloading
(self)
Perform method and content type overloading. Provides support for browser PUT, PATCH, DELETE & other requests, by specifying a '_method' form field. Also provides support for browser non-form requests (eg JSON), by specifying '_content' and '_content_type' form fields.
Perform method and content type overloading.
139
171
def _perform_method_overloading(self): """ Perform method and content type overloading. Provides support for browser PUT, PATCH, DELETE & other requests, by specifying a '_method' form field. Also provides support for browser non-form requests (eg JSON), by specifying '_content' and '_content_type' form fields. """ if not hasattr(self, "_method"): self.method = super().method self._stream = super().stream self._content_type = self.headers.get("Content-Type") self._content_length = get_content_length(self.environ) if ( self._method == "POST" and self._content_type == "application/x-www-form-urlencoded" ): # Read the request data, then push it back onto the stream again. body = self.get_data() data = url_decode_stream(io.BytesIO(body)) self._stream = io.BytesIO(body) if "_method" in data: # Support browser forms with PUT, PATCH, DELETE & other methods. self._method = data["_method"] if "_content" in data and "_content_type" in data: # Support browser forms with non-form data, such as JSON. body = data["_content"].encode("utf8") self._stream = io.BytesIO(body) self._content_type = data["_content_type"] self._content_length = len(body)
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L139-L171
3
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28 ]
81.818182
[ 11, 26, 29, 30, 31, 32 ]
18.181818
false
90.990991
33
7
81.818182
7
def _perform_method_overloading(self): if not hasattr(self, "_method"): self.method = super().method self._stream = super().stream self._content_type = self.headers.get("Content-Type") self._content_length = get_content_length(self.environ) if ( self._method == "POST" and self._content_type == "application/x-www-form-urlencoded" ): # Read the request data, then push it back onto the stream again. body = self.get_data() data = url_decode_stream(io.BytesIO(body)) self._stream = io.BytesIO(body) if "_method" in data: # Support browser forms with PUT, PATCH, DELETE & other methods. self._method = data["_method"] if "_content" in data and "_content_type" in data: # Support browser forms with non-form data, such as JSON. body = data["_content"].encode("utf8") self._stream = io.BytesIO(body) self._content_type = data["_content_type"] self._content_length = len(body)
1,637
flask-api/flask-api
fdba680df667662e683bf69e0516e3ffef3f51bc
flask_api/request.py
APIRequest.full_path
(self)
return self.path + "?" + self.query_string.decode()
Werzueg's full_path implementation always appends '?', even when the query string is empty. Let's fix that.
Werzueg's full_path implementation always appends '?', even when the query string is empty. Let's fix that.
176
183
def full_path(self): """ Werzueg's full_path implementation always appends '?', even when the query string is empty. Let's fix that. """ if not self.query_string: return self.path return self.path + "?" + self.query_string.decode()
https://github.com/flask-api/flask-api/blob/fdba680df667662e683bf69e0516e3ffef3f51bc/project3/flask_api/request.py#L176-L183
3
[ 0, 1, 2, 3, 4, 5, 7 ]
87.5
[ 6 ]
12.5
false
90.990991
8
2
87.5
2
def full_path(self): if not self.query_string: return self.path return self.path + "?" + self.query_string.decode()
1,638