CmvrControlStation/src/tcpcalibration.cpp

270 lines
12 KiB
C++
Raw Normal View History

#include "tcpcalibration.h"
#include <algorithm>
#include <cmath>
#include <limits>
namespace TcpCalibration {
namespace {
constexpr double pi = 3.14159265358979323846;
bool fail(QString *error, const char *message)
{
if (error) *error = QString::fromUtf8(message);
return false;
}
void clearError(QString *error) { if (error) error->clear(); }
Matrix multiply(const Matrix &a, const Matrix &b)
{
Matrix out{};
for (int r=0;r<4;++r) for (int c=0;c<4;++c)
for (int k=0;k<4;++k) out[r*4+c]+=a[r*4+k]*b[k*4+c];
return out;
}
}
bool validPose(const Pose &pose)
{
return std::all_of(pose.begin(),pose.end(),[](double x){return std::isfinite(x);});
}
bool poseMatrix(const Pose &p, Matrix &matrix, QString *error)
{
if (!validPose(p)) return fail(error,"Pose must contain six finite values.");
const double cx=std::cos(p[3]), sx=std::sin(p[3]);
const double cy=std::cos(p[4]), sy=std::sin(p[4]);
const double cz=std::cos(p[5]), sz=std::sin(p[5]);
matrix={{cz*cy,cz*sy*sx-sz*cx,cz*sy*cx+sz*sx,p[0],
sz*cy,sz*sy*sx+cz*cx,sz*sy*cx-cz*sx,p[1],
-sy,cy*sx,cy*cx,p[2],0,0,0,1}};
clearError(error); return true;
}
bool matrixPose(const Matrix &m, Pose &pose, QString *error)
{
for (double v:m) if (!std::isfinite(v)) return fail(error,"Transform contains non-finite values.");
constexpr double tolerance=1e-6;
if (std::abs(m[12])>tolerance || std::abs(m[13])>tolerance ||
std::abs(m[14])>tolerance || std::abs(m[15]-1)>tolerance)
return fail(error,"Transform must have homogeneous last row [0,0,0,1].");
for (int a=0;a<3;++a) for (int b=0;b<3;++b) {
double dot=0;
for (int r=0;r<3;++r) dot+=m[r*4+a]*m[r*4+b];
if (std::abs(dot-(a==b?1.0:0.0))>tolerance)
return fail(error,"Transform rotation must be orthonormal.");
}
const double determinant=m[0]*(m[5]*m[10]-m[6]*m[9])
-m[1]*(m[4]*m[10]-m[6]*m[8])+m[2]*(m[4]*m[9]-m[5]*m[8]);
if (std::abs(determinant-1)>tolerance)
return fail(error,"Transform rotation must be proper (determinant +1).");
const double cy=std::hypot(m[0],m[4]);
Pose out{{m[3],m[7],m[11],0,std::atan2(-m[8],cy),0}};
// Same gimbal-lock branch as phone/scripts/robot_pose_math.py.
if (cy>1e-9) {out[3]=std::atan2(m[9],m[10]); out[5]=std::atan2(m[4],m[0]);}
else out[3]=std::atan2(-m[6],m[5]);
pose=out; clearError(error); return true;
}
bool toolPose(const Pose &baseFlange, const Pose &flangeTcp, Pose &baseTcp, QString *error)
{
Matrix a{},b{};
if (!poseMatrix(baseFlange,a,error) || !poseMatrix(flangeTcp,b,error)) return false;
return matrixPose(multiply(a,b),baseTcp,error);
}
bool flangePose(const Pose &baseTcp, const Pose &flangeTcp, Pose &baseFlange, QString *error)
{
Matrix a{},b{},inverse{};
if (!poseMatrix(baseTcp,a,error) || !poseMatrix(flangeTcp,b,error)) return false;
for (int r=0;r<3;++r) {
for (int c=0;c<3;++c) inverse[r*4+c]=b[c*4+r];
for (int c=0;c<3;++c) inverse[r*4+3]-=inverse[r*4+c]*b[c*4+3];
}
inverse[15]=1;
return matrixPose(multiply(a,inverse),baseFlange,error);
}
bool jogTarget(const Pose &baseActive, const Pose &flangeActive, const Pose &flangeSelected,
int axis, double increment, Pose &target, QString *error)
{
if (axis < 0 || axis >= 6 || !std::isfinite(increment)
|| std::abs(increment) > (axis < 3 ? .002 : .005))
return fail(error, "TCP jog increment is outside the bounded step range.");
Pose flange{}, selected{}, delta{}, nextSelected{}, nextFlange{};
if (!flangePose(baseActive, flangeActive, flange, error)
|| !toolPose(flange, flangeSelected, selected, error)) return false;
delta[size_t(axis)] = increment;
return toolPose(selected, delta, nextSelected, error)
&& flangePose(nextSelected, flangeSelected, nextFlange, error)
&& toolPose(nextFlange, flangeActive, target, error);
}
bool tooSimilar(const Pose &previous, const Pose &current)
{
Matrix a{},b{};
if (!poseMatrix(previous,a) || !poseMatrix(current,b)) return false;
const double distance=std::hypot(std::hypot(current[0]-previous[0],
current[1]-previous[1]),current[2]-previous[2])*1000;
double trace=0;
for (int r=0;r<3;++r) for (int c=0;c<3;++c) trace+=a[r*4+c]*b[r*4+c];
const double angle=std::acos(std::max(-1.0,std::min(1.0,(trace-1)/2)))*180/pi;
return distance<1.0 && angle<3.0;
}
namespace {
bool solvePosition(const std::vector<Pose> &poses, Result &result, QString *error)
{
if (poses.size()<3) return fail(error,"TCP position calibration needs at least three flange poses.");
std::vector<Matrix> transforms;
std::vector<std::array<double,6>> a;
std::vector<double> b;
for (const Pose &pose:poses) {
Matrix m{};
if (!poseMatrix(pose,m,error)) return false;
transforms.push_back(m);
for (int r=0;r<3;++r) {
std::array<double,6> row{{m[r*4],m[r*4+1],m[r*4+2],0,0,0}};
row[3+r]=-1; a.push_back(row); b.push_back(-m[r*4+3]);
}
}
// One-sided Jacobi SVD: orthogonalize A's six columns directly. Never form
// A^T*A (which would square the condition number). A becomes U*Sigma;
// V accumulates the right rotations, so x=V*Sigma^-1*U^T*b.
std::array<std::array<double,6>,6> v{};
for (int i=0;i<6;++i) v[i][i]=1;
const double epsilon=std::numeric_limits<double>::epsilon();
bool converged=false;
for (int sweep=0;sweep<100;++sweep) {
bool changed=false;
for (int p=0;p<5;++p) for (int q=p+1;q<6;++q) {
double alpha=0,beta=0,gamma=0;
for (const auto &row:a) {alpha+=row[p]*row[p];beta+=row[q]*row[q];gamma+=row[p]*row[q];}
if (std::abs(gamma)<=16*epsilon*std::sqrt(alpha)*std::sqrt(beta)) continue;
changed=true;
const double zeta=(beta-alpha)/(2*gamma);
const double tangent=std::copysign(1.0,zeta)/(std::abs(zeta)+std::hypot(1.0,zeta));
const double cosine=1/std::hypot(1.0,tangent), sine=cosine*tangent;
for (auto &row:a) {const double x=row[p],y=row[q];row[p]=cosine*x-sine*y;row[q]=sine*x+cosine*y;}
for (auto &row:v) {const double x=row[p],y=row[q];row[p]=cosine*x-sine*y;row[q]=sine*x+cosine*y;}
}
if (!changed) {converged=true;break;}
}
if (!converged) return fail(error,"TCP least-squares decomposition did not converge.");
std::array<double,6> singular{};
for (int c=0;c<6;++c) for (const auto &row:a) singular[c]=std::hypot(singular[c],row[c]);
const double largest=*std::max_element(singular.begin(),singular.end());
const double smallest=*std::min_element(singular.begin(),singular.end());
// NumPy lstsq(rcond=None): epsilon * max(M,N) * largest singular value.
if (smallest<=epsilon*double(std::max(size_t(6),a.size()))*largest)
return fail(error,"Insufficient rotation diversity: TCP system rank is below six.");
// Additional explicit numerical guard, absent from the phone implementation.
if (smallest<largest/1e8)
return fail(error,"TCP poses are ill-conditioned; increase wrist rotation diversity.");
std::array<double,6> solution{};
for (int c=0;c<6;++c) {
double projection=0;
for (size_t r=0;r<a.size();++r) projection+=(a[r][c]/singular[c])*b[r];
const double coefficient=projection/singular[c];
for (int j=0;j<6;++j) solution[j]+=v[j][c]*coefficient;
}
Result out;
for (int i=0;i<3;++i) {out.offset[i]=solution[i];out.fixedPoint[i]=solution[i+3];}
for (double value:solution) if (!std::isfinite(value))
return fail(error,"TCP solution is non-finite.");
double residualNorm=0;
for (const Matrix &m:transforms) {
double distance=0;
for (int r=0;r<3;++r) {
double delta=m[r*4+3]-out.fixedPoint[r];
for (int c=0;c<3;++c) delta+=m[r*4+c]*out.offset[c];
distance=std::hypot(distance,delta);
}
const double mm=distance*1000;
if (!std::isfinite(mm)) return fail(error,"TCP residual is non-finite.");
out.residualsMm.push_back(mm); residualNorm=std::hypot(residualNorm,mm);
}
out.rmsMm=residualNorm/std::sqrt(double(poses.size()));
if (!std::isfinite(out.rmsMm)) return fail(error,"TCP RMS is non-finite.");
result=out; clearError(error); return true;
}
}
bool solve(const std::vector<Pose> &poses, Result &result, QString *error)
{
if (poses.size()<4) return fail(error,"TCP calibration needs at least four flange poses.");
return solvePosition(poses,result,error);
}
bool solveSixPoint(const std::vector<Pose> &poses, DirectionMethod method,
Result &result, QString *error)
{
if (poses.size()!=6) return fail(error,"Six-point TCP calibration needs exactly six flange poses.");
if (method!=DirectionMethod::XZ && method!=DirectionMethod::XY)
return fail(error,"Unknown six-point direction method.");
Result out;
if (!solvePosition(std::vector<Pose>(poses.begin(),poses.begin()+3),out,error)) return false;
std::array<Matrix,3> direction{};
std::array<std::array<double,3>,3> tip{};
for (int i=0;i<3;++i) {
if (!poseMatrix(poses[size_t(i+3)],direction[i],error)) return false;
const auto &m=direction[i];
for (int r=0;r<3;++r) {
tip[i][r]=m[r*4+3];
for (int c=0;c<3;++c) tip[i][r]+=m[r*4+c]*out.offset[c];
if (!std::isfinite(tip[i][r])) return fail(error,"Direction TCP position is non-finite.");
}
if (i) {
double trace=0;
for(int r=0;r<3;++r) for(int c=0;c<3;++c) trace+=direction[0][r*4+c]*m[r*4+c];
const double angle=std::acos(std::max(-1.0,std::min(1.0,(trace-1)/2)))*180/pi;
out.directionOrientationDriftDeg=std::max(out.directionOrientationDriftDeg,angle);
if (angle>.2+1e-9)
return fail(error,"Direction poses must keep flange orientation fixed (maximum drift 0.2 degrees).");
}
}
using Vector=std::array<double,3>;
std::array<Vector,2> vectors{};
for (int i=0;i<2;++i) {
double length=0;
for (int r=0;r<3;++r) {
vectors[i][r]=tip[i+1][r]-tip[0][r];
length=std::hypot(length,vectors[i][r]);
}
// Conservative numerical floor; vendor-specific larger travel guidance
// belongs in the teaching instructions, not a universal algorithm gate.
if (!std::isfinite(length) || length<.01)
return fail(error,"Direction teaching baseline must be at least 10 mm and finite.");
out.directionBaselineMm[i]=length*1000;
if (!std::isfinite(out.directionBaselineMm[i]))
return fail(error,"Direction baseline is non-finite.");
for(double &value:vectors[i]) value/=length;
}
const Vector x=vectors[0];
double dot=0;
for(int r=0;r<3;++r) dot+=x[r]*vectors[1][r];
dot=std::max(-1.0,std::min(1.0,dot));
out.directionAngleDeg=std::acos(dot)*180/pi;
if (out.directionAngleDeg<5 || out.directionAngleDeg>175)
return fail(error,"Direction vectors are nearly collinear; separation must be 5 to 175 degrees.");
Vector secondary{};
double norm=0;
for(int r=0;r<3;++r) { secondary[r]=vectors[1][r]-dot*x[r]; norm=std::hypot(norm,secondary[r]); }
for(double &value:secondary) value/=norm;
auto cross=[](const Vector &a,const Vector &b)->Vector {
return {{a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]}};
};
Vector y{},z{};
if (method==DirectionMethod::XZ) { z=secondary; y=cross(z,x); }
else { y=secondary; z=cross(x,y); }
const std::array<Vector,3> axes{{x,y,z}};
Matrix flangeTool{}; flangeTool[15]=1;
// Directions were taught in base coordinates. Persist flange-relative
// rotation R_flange_tool = transpose(R_base_flange_origin) * R_base_tool.
for(int r=0;r<3;++r) {
flangeTool[r*4+3]=out.offset[r];
for(int c=0;c<3;++c) for(int k=0;k<3;++k)
flangeTool[r*4+c]+=direction[0][k*4+r]*axes[c][k];
}
if (!matrixPose(flangeTool,out.offset,error)) return false;
result=out; clearError(error); return true;
}
}