ML Code
ML Code
and functionality.', 'tool': None}, {'description': 'Choose a suitable ML model for the task of bone
alignment (e.g., regression model, classification model, or neural network).', 'tool': None},
{'description': 'Gather and preprocess the training data required for the ML model. Split the data
into training and testing sets.', 'tool': None}, {'description': "Implement the code to train the selected
ML model using the training data. Evaluate the model's performance using the testing data.", 'tool':
None}, {'description': 'Modify the existing Python code to include the trained ML model. Ensure that
the model can make predictions based on the input data from the robot.', 'tool': None},
{'description': 'Run tests to ensure that the integrated system works as expected. Validate the
performance of the robot with the integrated ML model.', 'tool': None}]}
Let's start by reviewing the existing Python code for the robot to understand its structure and
functionality. Please provide the Python code for the robot named "AUTOMATION OF FRACTURED
FEMUR BONE ALIGNMENT USING PARALLEL ROBOT".
Great! Let's proceed with the integration of an ML model into this code. Here are the steps we will
follow:
1. Review the existing Python code for the robot to understand its structure and
functionality. (Done)
3. Gather and preprocess the training data required for the ML model. Split the data into
training and testing sets.
4. Implement the code to train the selected ML model using the training data. Evaluate the
model's performance using the testing data.
5. Modify the existing Python code to include the trained ML model. Ensure that the model
can make predictions based on the input data from the robot.
6. Run tests to ensure that the integrated system works as expected. Validate the
performance of the robot with the integrated ML model.
For the task of bone alignment, a regression model would be suitable as we are predicting
continuous values (positions and angles). We can use a neural network regression model for this
purpose.
We need training data that includes the input features (e.g., current positions and angles) and the
target outputs (desired positions and angles). For this example, let's assume we have a
dataset bone_alignment_data.csv.
Step 4: Implement the Code to Train the ML Model
Let's start by creating a new Python file train_model.py to implement the training code.
Let's write the code to train a neural network regression model using the training data. We will use
TensorFlow and Keras for this purpose.
The training script has been created successfully. Now, let's install the required packages and run the
training script.
def wait(s):
sleep(s)
class Actuators:
def __init__(self, port='COM14', baudrate=1000000):
self.portHandler = PortHandler(port)
self.packetHandler = PacketHandler(1.0)
self.groupSyncWrite = GroupSyncWrite(self.portHandler,
self.packetHandler, 30, 4)
self.portHandler.openPort()
self.portHandler.setBaudRate(baudrate)
wait(1)
found_ids = self.ping()
print(f"Detected actuator IDs: {found_ids}")
if len(found_ids) < 6:
raise Exception('Actuators Count Error')
for i in range(len(goal_positions)):
dxl_addparam_result = self.groupSyncWrite.addParam(i + 1,
goal_positions[i])
if dxl_addparam_result != True:
print('False')
self.groupSyncWrite.txPacket()
self.groupSyncWrite.clearParam()
def ping(self):
found_ids = []
for i in range(1, 10):
dxl_model_number, dxl_comm_result, dxl_error =
self.packetHandler.ping(self.portHandler, i)
if dxl_comm_result == COMM_SUCCESS:
found_ids.append(i)
return found_ids
def close(self):
self.portHandler.closePort()
class Robot:
motorH = 102.30
HOME_Z = 295.92
RELATIVE = 'rel'
ABSOLUTE = 'abs'
x, y, z, roll, pitch, yaw = 0, 0, HOME_Z, 0, 0, 0
LINK_1 = 80.0
LINK_2 = 220.0
platform = np.array(
[[23.56, 141.78, 0, 1], [-23.56, 141.78, 0, 1], [-134.57, -50.49, 0, 1],
[-110.77, -91.59, 0, 1],
[110.77, -91.59, 0, 1], [134.57, -50.49, 0, 1]])
base = np.array([[58.66, 144.14, 0, 1], [-58.66, 144.14, 0, 1], [-154.15, -
21.27, 0, 1], [-95.5, -122.86, 0, 1],
[95.5, -122.86, 0, 1], [154.15, -21.27, 0, 1]])
self.LINK_1 = LINK_1
self.LINK_2 = LINK_2
self.link_1_correction = link_1_correction
self.link_2_correction = link_2_correction
def close(self):
self.actuators.close()
def reset(self):
self.goto()
def tool(self, x=0, y=0, z=0):
self.tool_x, self.tool_y, self.tool_z = x, y, z
hs = self.platform
sh = self.base
# Applying transformation
hs = np.matmul(hs, translation(-self.tool_x, -self.tool_y, -self.tool_z))
hs = np.matmul(hs, rotation(rad(self.roll), rad(self.pitch),
rad(self.yaw)))
hs = np.matmul(hs, translation(self.tool_x, self.tool_y, self.tool_z))
hs = np.matmul(hs, translation(self.x, self.y, self.z - self.motorH))
# iKin
l1o = np.array([[hs[0][0] - sh[0][0]], [hs[0][1] - sh[0][1]], [hs[0][2] -
sh[0][2]]])
l2o = np.array([[hs[1][0] - sh[1][0]], [hs[1][1] - sh[1][1]], [hs[1][2] -
sh[1][2]]])
l3o = np.array([[hs[2][0] - sh[2][0]], [hs[2][1] - sh[2][1]], [hs[2][2] -
sh[2][2]]])
l4o = np.array([[hs[3][0] - sh[3][0]], [hs[3][1] - sh[3][1]], [hs[3][2] -
sh[3][2]]])
l5o = np.array([[hs[4][0] - sh[4][0]], [hs[4][1] - sh[4][1]], [hs[4][2] -
sh[4][2]]])
l6o = np.array([[hs[5][0] - sh[5][0]], [hs[5][1] - sh[5][1]], [hs[5][2] -
sh[5][2]]])
l1 = np.matmul(rotation_z(rad(-150)).transpose(), l1o)
l2 = np.matmul(rotation_z(rad(150)).transpose(), l2o)
l3 = np.matmul(rotation_z(rad(-30)).transpose(), l3o)
l4 = np.matmul(rotation_z(rad(-90)).transpose(), l4o)
l5 = np.matmul(rotation_z(rad(90)).transpose(), l5o)
l6 = np.matmul(rotation_z(rad(30)).transpose(), l6o)
A1 = sqrt(
(link1[0] + link2[0] * cos(thetav1) * cos(theta21)) ** 2 + (link2[0]
* cos(thetav1) * sin(theta21)) ** 2);
A2 = sqrt(
(link1[1] + link2[1] * cos(thetav2) * cos(theta22)) ** 2 + (link2[1]
* cos(thetav2) * sin(theta22)) ** 2);
A3 = sqrt(
(link1[2] + link2[2] * cos(thetav3) * cos(theta23)) ** 2 + (link2[2]
* cos(thetav3) * sin(theta23)) ** 2);
A4 = sqrt(
(link1[3] + link2[3] * cos(thetav4) * cos(theta24)) ** 2 + (link2[3]
* cos(thetav4) * sin(theta24)) ** 2);
A5 = sqrt(
(link1[4] + link2[4] * cos(thetav5) * cos(theta25)) ** 2 + (link2[4]
* cos(thetav5) * sin(theta25)) ** 2);
A6 = sqrt(
(link1[5] + link2[5] * cos(thetav6) * cos(theta26)) ** 2 + (link2[5]
* cos(thetav6) * sin(theta26)) ** 2);
self.actuators.move_position(
[-deg(self.theta11), deg(self.theta12), -deg(self.theta13),
deg(self.theta14), -deg(self.theta15),
deg(self.theta16)])
return [self.theta11, self.theta12, self.theta13, self.theta14,
self.theta15, self.theta16]
def update(self):
self.goto(self.x, self.y, self.z, self.roll, self.pitch, self.yaw)
# Make predictions
predictions = model.predict(input_data)
target_x, target_y, target_z, target_roll, target_pitch, target_yaw =
predictions[0]
If you have any further questions or need additional modifications, feel free
to ask!
""" matrix.py: Matrix class for matrix operations. """
import random
import operator
import sys
import unittest
import numpy as np
__version__ = "0.47"
def rotation_z(angleZ):
sinZ = sin(angleZ)
cosZ = cos(angleZ)
return rot
cosX = cos(angleX);
sinX = sin(angleX);
cosY = cos(angleY);
sinY = sin(angleY);
cosZ = cos(angleZ);
sinZ = sin(angleZ);
m_sinX = -sinX;
m_sinY = -sinY;
m_sinZ = -sinZ;
rot = np.array([[cosY * cosZ, m_sinX * m_sinY * cosZ + cosX * sinZ, cosX * m_sinY * cosZ + sinX *
sinZ, 0],
[cosY * m_sinZ, m_sinX * m_sinY * m_sinZ + cosX * cosZ, cosX * m_sinY * m_sinZ + sinX *
cosZ, 0],
[0, 0, 0, 1]])
return rot
return trans
class MatrixError(Exception):
pass
class Matrix(object):
if init:
else:
self.rows = []
self.m = m
self.n = n
return self.rows[idx]
self.rows[idx] = item
def __str__(self):
return s + '\n'
def __repr__(self):
s = str(self.rows)
rank = str(self.getRank())
return rep
def reset(self):
""" Reset the matrix data """
return self;
def transpose(self):
return self;
def getTranspose(self):
m, n = self.n, self.m
mat = Matrix(m, n)
return mat
def getRank(self):
if self.getRank() != mat.getRank():
for x in range(self.m):
ret[x] = row
return ret
if self.getRank() != mat.getRank():
ret[x] = row
return ret
if (self.n != mat.m):
mat_t = mat.getTranspose()
for x in range(self.m):
for y in range(mat_t.m):
return mulmat
# Calls __add__
self.rows = tempmat.rows[:]
return self
# Calls __sub__
self.rows = tempmat.rows[:]
return self
# rank as well...
# Calls __mul__
return self
open(filename, 'w').write(str(self))
@classmethod
m = len(rows)
n = len(rows[0])
# Validity check
mat.rows = rows
return mat
@classmethod
for x in range(m):
@classmethod
return cls.fromList(rows)
@classmethod
if m != n:
rows = cls.makeZero(m, n)
return cls.fromList(rows)
@classmethod
idx = 0
for row in rows:
row[idx] = 1
idx += 1
return cls.fromList(rows)
@classmethod
def readStdin(cls):
rows = []
while True:
line = sys.stdin.readline().strip()
rows.append(row)
return cls._makeMatrix(rows)
@classmethod
rows = []
rows.append(row)
return cls._makeMatrix(rows)
@classmethod
of lists """
rows = listoflists[:]
return cls._makeMatrix(rows)
def wait(s):
sleep(s)
self.portHandler = PortHandler(port)
self.packetHandler = PacketHandler(1.0)
self.portHandler.openPort()
self.portHandler.setBaudRate(baudrate)
wait(1)
if len(self.ping()) < 6:
goal_positions = [[DXL_LOBYTE(DXL_LOWORD(i)),
DXL_HIBYTE(DXL_LOWORD(i)),
DXL_LOBYTE(DXL_HIWORD(i)),
for i in range(len(goal_positions)):
if dxl_addparam_result != True:
print('False')
self.groupSyncWrite.txPacket()
self.groupSyncWrite.clearParam()
# Depreciated
# Depreciated
# Depreciated
for i in pattern:
self.set_led_single(i, state)
def ping(self):
found_ids = []
if dxl_comm_result == COMM_SUCCESS:
found_ids.append(i)
return found_ids
def close(self):
self.portHandler.closePort()
import pypot.dynamixel.conversion
import os
import numpy as np
def rad(deg):
def deg(rad):
class Robot:
motorH = 102.30
HOME_Z = 295.92
RELATIVE = 'rel'
ABSOLUTE = 'abs'
LINK_2 = 220.0
platform = np.array(
[[23.56, 141.78, 0, 1], [-23.56, 141.78, 0, 1], [-134.57, -50.49, 0, 1], [-110.77, -91.59, 0, 1],
base = np.array([[58.66, 144.14, 0, 1], [-58.66, 144.14, 0, 1], [-154.15, -21.27, 0, 1], [-95.5, -122.86,
0, 1],
link_2_correction=DEFAULT_LINK_2_CORR):
self.actuators = Actuators(port)
self.LINK_1 = LINK_1
self.LINK_2 = LINK_2
self.link_1_correction = link_1_correction
self.link_2_correction = link_2_correction
self.actuators.set_led([i], j)
wait(0.07)
wait(0.1)
def close(self):
self.actuators.close()
def reset(self):
self.goto()
hs = self.platform
sh = self.base
# Applying transformation
# iKin
l1 = np.matmul(rotation_z(rad(-150)).transpose(), l1o)
l2 = np.matmul(rotation_z(rad(150)).transpose(), l2o)
l3 = np.matmul(rotation_z(rad(-30)).transpose(), l3o)
l4 = np.matmul(rotation_z(rad(-90)).transpose(), l4o)
l5 = np.matmul(rotation_z(rad(90)).transpose(), l5o)
l6 = np.matmul(rotation_z(rad(30)).transpose(), l6o)
A1 = sqrt(
A2 = sqrt(
A3 = sqrt(
A4 = sqrt(
A5 = sqrt(
A6 = sqrt(
self.actuators.move_position(
deg(self.theta16)])
def update(self):
dx, dy, dz, droll, dpitch, dyaw = x / steps, y / steps, z / steps, roll / steps, pitch / steps, yaw /
steps
for i in tqdm(range(steps)):
wait(T / steps)
def move_absolute(self, x=0, y=0, z=HOME_Z, roll=0, pitch=0, yaw=0, T=2, steps=100):
self.move_relative(x=(x - self.x),
y=(y - self.y),
z=(z - self.z),
roll=(roll - self.roll),
pitch=(pitch - self.pitch),
yaw=(yaw - self.yaw),
T=T,
steps=steps)
""" matrix.py: Matrix class for matrix operations. """
import random
import operator
import sys
import unittest
import numpy as np
__version__ = "0.47"
def rotation_z(angleZ):
sinZ = sin(angleZ)
cosZ = cos(angleZ)
return rot
cosX = cos(angleX);
sinX = sin(angleX);
cosY = cos(angleY);
sinY = sin(angleY);
cosZ = cos(angleZ);
sinZ = sin(angleZ);
m_sinX = -sinX;
m_sinY = -sinY;
m_sinZ = -sinZ;
rot = np.array([[cosY * cosZ, m_sinX * m_sinY * cosZ + cosX * sinZ, cosX * m_sinY * cosZ + sinX *
sinZ, 0],
[cosY * m_sinZ, m_sinX * m_sinY * m_sinZ + cosX * cosZ, cosX * m_sinY * m_sinZ + sinX *
cosZ, 0],
[0, 0, 0, 1]])
return rot
return trans
class MatrixError(Exception):
pass
class Matrix(object):
if init:
else:
self.rows = []
self.m = m
self.n = n
return self.rows[idx]
self.rows[idx] = item
def __str__(self):
return s + '\n'
def __repr__(self):
s = str(self.rows)
rank = str(self.getRank())
return rep
def reset(self):
""" Reset the matrix data """
return self;
def transpose(self):
return self;
def getTranspose(self):
m, n = self.n, self.m
mat = Matrix(m, n)
return mat
def getRank(self):
if self.getRank() != mat.getRank():
for x in range(self.m):
ret[x] = row
return ret
if self.getRank() != mat.getRank():
ret[x] = row
return ret
if (self.n != mat.m):
mat_t = mat.getTranspose()
for x in range(self.m):
for y in range(mat_t.m):
return mulmat
# Calls __add__
self.rows = tempmat.rows[:]
return self
# Calls __sub__
self.rows = tempmat.rows[:]
return self
# rank as well...
# Calls __mul__
return self
open(filename, 'w').write(str(self))
@classmethod
m = len(rows)
n = len(rows[0])
# Validity check
mat.rows = rows
return mat
@classmethod
for x in range(m):
@classmethod
return cls.fromList(rows)
@classmethod
if m != n:
rows = cls.makeZero(m, n)
return cls.fromList(rows)
@classmethod
idx = 0
for row in rows:
row[idx] = 1
idx += 1
return cls.fromList(rows)
@classmethod
def readStdin(cls):
rows = []
while True:
line = sys.stdin.readline().strip()
rows.append(row)
return cls._makeMatrix(rows)
@classmethod
rows = []
rows.append(row)
return cls._makeMatrix(rows)
@classmethod
of lists """
rows = listoflists[:]
return cls._makeMatrix(rows)
def wait(s):
sleep(s)
self.portHandler = PortHandler(port)
self.packetHandler = PacketHandler(1.0)
self.portHandler.openPort()
self.portHandler.setBaudRate(baudrate)
wait(1)
if len(self.ping()) < 6:
goal_positions = [[DXL_LOBYTE(DXL_LOWORD(i)),
DXL_HIBYTE(DXL_LOWORD(i)),
DXL_LOBYTE(DXL_HIWORD(i)),
for i in range(len(goal_positions)):
if dxl_addparam_result != True:
print('False')
self.groupSyncWrite.txPacket()
self.groupSyncWrite.clearParam()
# Depreciated
# Depreciated
# Depreciated
for i in pattern:
self.set_led_single(i, state)
def ping(self):
found_ids = []
if dxl_comm_result == COMM_SUCCESS:
found_ids.append(i)
return found_ids
def close(self):
self.portHandler.closePort()
import pypot.dynamixel.conversion
import os
import numpy as np
def rad(deg):
def deg(rad):
class Robot:
motorH = 102.30
HOME_Z = 295.92
RELATIVE = 'rel'
ABSOLUTE = 'abs'
LINK_2 = 220.0
platform = np.array(
[[23.56, 141.78, 0, 1], [-23.56, 141.78, 0, 1], [-134.57, -50.49, 0, 1], [-110.77, -91.59, 0, 1],
base = np.array([[58.66, 144.14, 0, 1], [-58.66, 144.14, 0, 1], [-154.15, -21.27, 0, 1], [-95.5, -122.86,
0, 1],
link_2_correction=DEFAULT_LINK_2_CORR):
self.actuators = Actuators(port)
self.LINK_1 = LINK_1
self.LINK_2 = LINK_2
self.link_1_correction = link_1_correction
self.link_2_correction = link_2_correction
self.actuators.set_led([i], j)
wait(0.07)
wait(0.1)
def close(self):
self.actuators.close()
def reset(self):
self.goto()
hs = self.platform
sh = self.base
# Applying transformation
# iKin
l1 = np.matmul(rotation_z(rad(-150)).transpose(), l1o)
l2 = np.matmul(rotation_z(rad(150)).transpose(), l2o)
l3 = np.matmul(rotation_z(rad(-30)).transpose(), l3o)
l4 = np.matmul(rotation_z(rad(-90)).transpose(), l4o)
l5 = np.matmul(rotation_z(rad(90)).transpose(), l5o)
l6 = np.matmul(rotation_z(rad(30)).transpose(), l6o)
A1 = sqrt(
A2 = sqrt(
A3 = sqrt(
A4 = sqrt(
A5 = sqrt(
A6 = sqrt(
self.actuators.move_position(
deg(self.theta16)])
def update(self):
dx, dy, dz, droll, dpitch, dyaw = x / steps, y / steps, z / steps, roll / steps, pitch / steps, yaw /
steps
for i in tqdm(range(steps)):
wait(T / steps)
def move_absolute(self, x=0, y=0, z=HOME_Z, roll=0, pitch=0, yaw=0, T=2, steps=100):
self.move_relative(x=(x - self.x),
y=(y - self.y),
z=(z - self.z),
roll=(roll - self.roll),
pitch=(pitch - self.pitch),
yaw=(yaw - self.yaw),
T=T,
steps=steps)