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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-    */
/* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */

/*
  Author(s):  Anton Deguet, Rishibrata Biswas, Adnan Munawar
  Created on: 2019-11-11

  (C) Copyright 2019-2020 Johns Hopkins University (JHU), All Rights Reserved.

  --- begin cisst license - do not edit ---

  This software is provided "as is" under an open source license, with
  no warranty.  The complete license can be found in license.txt and
  http://www.cisst.org/cisst/license.txt.

  --- end cisst license ---
*/

#include <sawIntuitiveResearchKit/robManipulatorMTM.h>
#include <math.h>

robManipulatorMTM::robManipulatorMTM(const std::vector<robKinematics *> linkParms,
                                     const vctFrame4x4<double> &Rtw0)
    : robManipulator(linkParms, Rtw0)
{
}

robManipulatorMTM::robManipulatorMTM(const std::string &robotfilename,
                                     const vctFrame4x4<double> &Rtw0)
    : robManipulator(robotfilename, Rtw0)
{
}

robManipulatorMTM::robManipulatorMTM(const vctFrame4x4<double> &Rtw0)
    : robManipulator(Rtw0)
{
}

robManipulator::Errno
robManipulatorMTM::InverseKinematics(vctDynamicVector<double> & q,
                                     const vctFrame4x4<double> & Rts,
                                     double CMN_UNUSED(tolerance),
                                     size_t CMN_UNUSED(Niterations),
                                     double CMN_UNUSED(LAMBDA))
{
    if (q.size() != links.size()) {
        std::stringstream ss;
        ss << "robManipulatorMTM::InverseKinematics: expected " << links.size()
           << " joints values but received " << q.size();
        mLastError = ss.str();
        CMN_LOG_RUN_ERROR << mLastError << std::endl;
        return robManipulator::EFAILURE;
    }

    if (links.size() == 0) {
        mLastError = "robManipulatorMTM::InverseKinematics: the manipulator has no links";
        CMN_LOG_RUN_ERROR << mLastError << std::endl;
        return robManipulator::EFAILURE;
    }

    // if we encounter a joint limit, keep computing a solution but at
    // the end return failure
    bool hasReachedJointLimit = false;

    // take Rtw0 into account
    vctFrm4x4 Rt07;
    Rtw0.ApplyInverseTo(Rts, Rt07);

    q[0] = atan2l(Rt07.Translation().X(),
                  -Rt07.Translation().Y());

    // arm is provided in ISI DH
    const double l1 = 0.2794;
    const double l1_sqr = l1 * l1;

    // create a triangle "above" forarm to find position
    const double forarmBase = 0.3645; // from ISI documentation
    const double forarmHeight = 0.1506; // for ISI documentation
    const double l2_sqr = forarmBase * forarmBase + forarmHeight * forarmHeight;
    const double l2 = sqrt(l2_sqr) ;
    const double angleOffset = asinl(forarmHeight / l2);

    // project in plane formed by links 2 & 3 to find q2 and q3 (joint[1] and joint[2])
    const double x = -Rt07.Translation().Z();
    const double y = sqrt(Rt07.Translation().X() * Rt07.Translation().X()
                          + Rt07.Translation().Y() * Rt07.Translation().Y());

    // 2 dof IK in plane
    const double d_sqr = x * x + y * y;
    const double d = sqrt(d_sqr);
    const double a1 = atan2l(y, x);
    const double a2 = acosl((l1_sqr - l2_sqr + d_sqr) / (2.0 * l1 * d));
    const double q1 = a1 - a2;
    const double q2 = -acosl((l1_sqr + l2_sqr - d_sqr) / (2.0 * l1 * l2));

    q[1] = q1;
    q[2] = q2 - angleOffset + cmnPI_2;

    // check joint limits for first 3 joints
    for (size_t joint = 0; joint < 3; joint++) {
        if (ClampJointValueAndUpdateError(joint, q[joint], 1e-5)) {
            hasReachedJointLimit = true;
        }
    }

    // optimized placement of platform
    // compute projection of roll axis on platform plane
    q[3] = FindOptimalPlatformAngle(q, Rt07);

//    // compute orientation of platform
//    const vctFrm4x4 Rt04 = this->ForwardKinematics(q, 4);
//    vctFrm4x4 Rt47;
//    Rt04.ApplyInverseTo(Rt07, Rt47);
//    vctEulerZXZRotation3 closed57(Rt47.Rotation());

//    // applying DH offsets
//    q[4] = closed57.alpha() + cmnPI_2;
//    q[5] = -closed57.beta() + cmnPI_2;
//    q[6] = closed57.gamma() + cmnPI;

    // Or Use this function to calculate all the joints in the Gimbal
    ComputeGimbalIK(q, Rt07);

    if (hasReachedJointLimit) {
        return robManipulator::EFAILURE;
    }

    return robManipulator::ESUCCESS;
}


int method = 2;
double q3_pre = 0.0;

double robManipulatorMTM::ComputeGimbalIK(vctDynamicVector<double> &q,
                                         const vctFrame4x4<double> &Rt07) const
{
    vctEulerYZXRotation3 euler_offset;
    // Rotation to align frame 7 with frame 4
    euler_offset.Assign(cmnPI_2, 0, -cmnPI_2);

    vctMatrixRotation3<double, true> Rt8;
    vctEulerToMatrixRotation3(euler_offset, Rt8);

    vctFrm4x4 Rt08, Rt78;
    Rt78.Rotation().Assign(Rt8);
    Rt08 = Rt07 * Rt78;

    const vctFrm4x4 Rt04 = ForwardKinematics(q, 4);

    vctFrm4x4 Rt48;
    Rt04.ApplyInverseTo(Rt08, Rt48);

    vctEulerZYXRotation3 closed48(Rt48.Rotation());

    double q3, q4, q5, q6;


    q4 = closed48.alpha();
    q5 = closed48.beta();
    q6 = -(closed48.gamma() - cmnPI);


//    std::cerr << "ZYZ :" << q[4] << ", " << q[5] << ", " << q[6] << "\n" ;
//    std::cerr << "ZYX :" << q4 << ", " << q5 << ", " << q6 << "\n" ;
//    std::cerr << "-----------\n";

    q[4] = q4;
    q[5] = q5;
    q[6] = q6;

    double scalar_mapping;
    double range;
    double centered_val;
    double normalized_val;

    // Limits for Wrist Pitch (Joint 5 at Index 4)
    // Consider the Wrist Pitch Joint at the Home position (0 Deg).
    // The upwards pitch corresponds to a negative angle and and
    // the downward pitch corresponds to a positive angle.
    // The Upper Limit A and B are two points defined for the upward
    // pitch angle and the Lower Limit A and B are two points defined
    // for the lower pitch angle. Based on where the position of the joint
    // angle is, a scalar mapping [-1.0 - 1.0] is calculated.
    // The scalar mapping is a function of q4, i.e. scalar_mapping(q4)
    // See the logic labeled Scalar Mapping Calculation Below

    // Changing the values of these two pairs of points, one
    // can change the attenuation as well the center point of direction
    // switching between each pair of points.

    // For example: consider lim_dn_a = 1.5 Rad and lim_dn_b = 2.0 Rad. The
    // midpoint for these two limits is:
    // mid_point_dn = 0.5 * (2.0 - 1.5) + 1.5
    // mid_point_dn => 1.75 Rad
    // Thus the scalar mapping at these three points, i.e. [lim_dn_a, mid_point_dn, lim_dn_b]
    // become:

    // scalar_mapping(lim_dn_a) =  1.0
    // scalar_mapping(mid_point_dn) =  0.0
    // scalar_mapping(lim_dn_b) = -1.0

    // And for all values in between
    // scalar_mapping(q4) = ((q4 - lim_dn_a) / (lim_dn_b - lim_dn_a) - 0.5) x 2.0

    double lim_up_a = -2.0; // Upper Limit A for Pitch Joint
    double lim_up_b = -1.5; // Upper Limit B for Pitch Joint
    double lim_dn_a = 1.2; // Lower Limit A for Pitch Joint
    double lim_dn_b = 1.8; // Lower Limit B for Pitch Joint

    // LOGIC:
    // SCALAR MAPPING CALCULATION
    if (lim_up_a < q[4] && q[4] < lim_up_b){
        range = lim_up_b - lim_up_a;
        normalized_val = (q[4] - lim_up_a) / range;
        centered_val = normalized_val - 0.5;
        scalar_mapping = centered_val * 2;
//            sign = 0;
    }
    else if (lim_up_b < q[4] && q[4] <= lim_dn_a){
        scalar_mapping = 1;
    }
    else if (lim_dn_a < q[4] && q[4] < lim_dn_b){
        range = lim_dn_b - lim_dn_a;
        normalized_val = (q[4] - lim_dn_a) / range;
        centered_val = normalized_val - 0.5;
        scalar_mapping = -centered_val * 2;
//            sign = 0;
    }
    else{
        scalar_mapping = -1;
    }

//        std::cerr << "\r" << "Scalar Mapping: " << scalar_mapping;

    double Kp_3 = 2.0;
    double Kd_3 = 0.1;
    double e;

    e = q[5];

    // Implicit dt incorporated into Kd_3
    q3 = Kp_3 * e * scalar_mapping + q[3] - Kd_3 * (q[3] - q3_pre);
    q3_pre = q[3];

    // make sure we respect joint limits
    const double q3Max = links[3].GetKinematics()->PositionMax();
    const double q3Min = links[3].GetKinematics()->PositionMin();
    if (q[3] > q3Max) {
        q[3] = q3Max;
    } else if (q[3] < q3Min) {
        q[3] = q3Min;
    }
}

// METHOD 0 -> RISHI'S METHOD
// METHOD 1 -> ADNAN'S METHOD
double robManipulatorMTM::FindOptimalPlatformAngle(const vctDynamicVector<double> & q,
                                                   const vctFrame4x4<double> & Rt07) const
{
    // RISHI'S METHOD
    if (method == 0) {
        const vctFrm4x4 Rt03 = ForwardKinematics(q, 3);
        vctFrm4x4 Rt37;
        Rt03.ApplyInverseTo(Rt07, Rt37);

        // find the angle difference between the gripper and the third joint to calculate auto-correct angle
        double angleDifference = acosl(-Rt37.Element(0, 2) /
                                       sqrt(Rt37.Element(1, 2) * Rt37.Element(1, 2) +
                                            Rt37.Element(0, 2) * Rt37.Element(0, 2)));
        if (Rt37.Element(1, 2) > 0.0) {
            angleDifference = -angleDifference;
        }

        // calculate Angle Option 1 (The correct choice when right-side-up)
        double option1 = angleDifference;

        // calculate Angle Option 2 (The correct choice when upside-down)
        double option2 = option1 - cmnPI;

        // Normalize within joint space
        if (option2 > cmnPI) {
            option2 -= 2.0 * cmnPI;
        } else if (option2 < (-3.0 * cmnPI_2)) {
            option2 += 2.0 * cmnPI;
        }

        // Normalize within joint space
        if ((option2 < -cmnPI)
                && (option2 > -3.0 * cmnPI_2)
                && (q[3] > 0.0)) {
            option2 += 2.0 * cmnPI;
        }

        // Normalize within joint space
        if ((option1 > cmnPI_2)
                && (option1 < cmnPI)
                && (q[3] < 0.0)) {
            option1 -= 2.0 * cmnPI;
        }

        // Choose either Option 1 or Option 2 based on which one is closer to the platform angle
        double solution;
        if (std::abs(q[3] - option2) < std::abs(q[3] - option1)) {
            solution = option2;
        } else {
            solution = option1;
        }

        // average with current position based on projection angle
        const double cosProjectionAngle = std::abs(cos(q[4]));
        double q3 = solution * cosProjectionAngle + q[3] * (1 - cosProjectionAngle);

        // make sure we respect joint limits
        const double q3Max = links[3].GetKinematics()->PositionMax();
        const double q3Min = links[3].GetKinematics()->PositionMin();
        if (q3 > q3Max) {
            q3 = q3Max;
        } else if (q3 < q3Min) {
            q3 = q3Min;
        }

        std::cerr << "\r" << "Joint 3 Value: " << q3 << std::endl;

        return q3;
    }

    // ADNAN'S METHOD
    else if (method==1){

        vctEulerYZXRotation3 euler_offset;
        // Rotation to align frame 7 with frame 4
        euler_offset.Assign(cmnPI_2, 0, -cmnPI_2);

        vctMatrixRotation3<double, true> Rt8;
        vctEulerToMatrixRotation3(euler_offset, Rt8);

        vctFrm4x4 Rt08, Rt78;
        Rt78.Rotation().Assign(Rt8);
        Rt08 = Rt07 * Rt78;

        const vctFrm4x4 Rt04 = ForwardKinematics(q, 4);

        vctFrm4x4 Rt48;
        Rt04.ApplyInverseTo(Rt08, Rt48);

        vctEulerZYXRotation3 closed48(Rt48.Rotation());

        // applying DH offsets
        const double q4 = closed48.alpha();
        const double q5 = closed48.beta();


        vctDynamicVector<double> qCopy(q);

//        ComputeGimbalIK(qCopy, Rt07);

        double scalar_mapping;
        double range;
        double centered_val;
        double normalized_val;

        // Limits for Wrist Pitch (Joint 5 at Index 4)
        // Consider the Wrist Pitch Joint at the Home position (0 Deg).
        // The upwards pitch corresponds to a negative angle and and
        // the downward pitch corresponds to a positive angle.
        // The Upper Limit A and B are two points defined for the upward
        // pitch angle and the Lower Limit A and B are two points defined
        // for the lower pitch angle. Based on where the position of the joint
        // angle is, a scalar mapping [-1.0 - 1.0] is calculated.
        // The scalar mapping is a function of q4, i.e. scalar_mapping(q4)
        // See the logic labeled Scalar Mapping Calculation Below

        // Changing the values of these two pairs of points, one
        // can change the attenuation as well the center point of direction
        // switching between each pair of points.

        // For example: consider lim_dn_a = 1.5 Rad and lim_dn_b = 2.0 Rad. The
        // midpoint for these two limits is:
        // mid_point_dn = 0.5 * (2.0 - 1.5) + 1.5
        // mid_point_dn => 1.75 Rad
        // Thus the scalar mapping at these three points, i.e. [lim_dn_a, mid_point_dn, lim_dn_b]
        // become:

        // scalar_mapping(lim_dn_a) =  1.0
        // scalar_mapping(mid_point_dn) =  0.0
        // scalar_mapping(lim_dn_b) = -1.0

        // And for all values in between
        // scalar_mapping(q4) = ((q4 - lim_dn_a) / (lim_dn_b - lim_dn_a) - 0.5) x 2.0

        double lim_up_a = -2.0; // Upper Limit A for Pitch Joint
        double lim_up_b = -1.5; // Upper Limit B for Pitch Joint
        double lim_dn_a = 1.0; // Lower Limit A for Pitch Joint
        double lim_dn_b = 2.0; // Lower Limit B for Pitch Joint

        // LOGIC:
        // SCALAR MAPPING CALCULATION
        if (lim_up_a < q4 && q4 < lim_up_b){
            range = lim_up_b - lim_up_a;
            normalized_val = (q4 - lim_up_a) / range;
            centered_val = normalized_val - 0.5;
            scalar_mapping = centered_val * 2;
//            scalar_mapping = 0;
        }
        else if (lim_up_b < q4 && q4 <= lim_dn_a){
            scalar_mapping = 1;
        }
        else if (lim_dn_a < q4 && q4 < lim_dn_b){
            range = lim_dn_b - lim_dn_a;
            normalized_val = (q4 - lim_dn_a) / range;
            centered_val = normalized_val - 0.5;
            scalar_mapping = -centered_val * 2;
//            scalar_mapping = 0;
        }
        else{
            scalar_mapping = -1;
        }

        double Kp_3 = 1.0;
        // double Kd_3 = 0.1;
        double e;
        double q3;

        e = q5;

        // Implicit dt incorporated into Kd_3
        double q3_increment = Kp_3 * q5 * scalar_mapping;
        const double max_q3_dot = cmnPI * 0.1; // assume kHz
        if (q3_increment > max_q3_dot) {
            q3_increment = max_q3_dot;
        } else if (q3_increment < -max_q3_dot) {
            q3_increment = -max_q3_dot;
        }
        q3 = q[3] + q3_increment;
//        q3 = Kp_3 * q5 * scalar_mapping + q[3]; // - Kd_3 * (q[3] - q3_pre);
        q3_pre = q[3];

        // make sure we respect joint limits
        const double q3Max = links[3].GetKinematics()->PositionMax();
        const double q3Min = links[3].GetKinematics()->PositionMin();
        if (q3 > q3Max) {
            q3 = q3Max;
        } else if (q3 < q3Min) {
            q3 = q3Min;
        }

        return q3;
    }
}