File: PrescribedMotionPlayground.cpp

package info (click to toggle)
simbody 3.7%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 72,896 kB
  • sloc: cpp: 248,827; ansic: 18,240; sh: 29; makefile: 24
file content (387 lines) | stat: -rw-r--r-- 15,041 bytes parent folder | download | duplicates (4)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
/* -------------------------------------------------------------------------- *
 *                               Simbody(tm)                                  *
 * -------------------------------------------------------------------------- *
 * This is part of the SimTK biosimulation toolkit originating from           *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody.  *
 *                                                                            *
 * Portions copyright (c) 2009-12 Stanford University and the Authors.        *
 * Authors: Michael Sherman                                                   *
 * Contributors:                                                              *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

/**@file
 * Adhoc main program for playing with prescribed motion.
 */

#include "SimTKsimbody.h"
#include "SimTKcommon/Testing.h"

#include <cstdio>
#include <exception>
#include <iostream>
using std::cout; using std::endl;
using std::clog; using std::cerr;

using namespace SimTK;

class MyReporter : public PeriodicEventReporter {
public:
    MyReporter(const MultibodySystem& system, 
        const Measure& power,
        const Measure& work,
        Real reportInterval)
    :   PeriodicEventReporter(reportInterval), 
        m_system(system), m_power(power), m_work(work)
    {}

    ~MyReporter() {}

    void handleEvent(const State& state) const override {
        cout << state.getTime() << " " << m_system.calcEnergy(state);
        cout << " " << m_power.getValue(state) << " " << m_work.getValue(state) 
            << " " << 
            m_system.calcEnergy(state) - m_work.getValue(state);
        //for (int i=0; i < state.getNQ(); ++i)
        //    cout << " " << state.getQ()[i];
        cout << "\n";
        const SimbodyMatterSubsystem& matter = m_system.getMatterSubsystem();
        cout << "qperr=" << matter.calcMotionErrors(state,Stage::Position) << "\n";
        cout << "uperr=" << matter.calcMotionErrors(state,Stage::Velocity) << "\n";
        cout << "qerr=" << state.getQErr() << "\n";
        cout << "uerr=" << state.getUErr() << "\n";
    }
private:
    const MultibodySystem& m_system;
    const Measure          m_power, m_work;
};


/* This Measure returns the instantaneous power being generated by the
constraints and motions. */
template <class T>
class PowerMeasure : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(PowerMeasure, Measure_<T>);

    PowerMeasure(Subsystem& sub, const SimbodyMatterSubsystem& matter)
    :   Measure_<T>(sub, new Implementation(matter), AbstractMeasure::SetHandle()) {}
    SimTK_MEASURE_HANDLE_POSTSCRIPT(PowerMeasure, Measure_<T>);
};


template <class T>
class PowerMeasure<T>::Implementation : public Measure_<T>::Implementation {
public:
    Implementation(const SimbodyMatterSubsystem& matter) 
    :   Measure_<T>::Implementation(1), m_matter(matter) {}

    // Default copy constructor, destructor, copy assignment are fine.

    // Implementations of virtual methods.
    Implementation* cloneVirtual() const {return new Implementation(*this);}
    int getNumTimeDerivativesVirtual() const {return 0;}
    Stage getDependsOnStageVirtual(int order) const 
    {   return Stage::Acceleration; }

    void calcCachedValueVirtual(const State& s, int derivOrder, T& value) const
    {
        SimTK_ASSERT1_ALWAYS(derivOrder==0,
            "PowerMeasure::Implementation::calcCachedValueVirtual():"
            " derivOrder %d seen but only 0 allowed.", derivOrder);

        value = m_matter.calcMotionPower(s) + m_matter.calcConstraintPower(s);
    }
private:
    const SimbodyMatterSubsystem& m_matter;
};

const Real RodLength = 1.1;
int main() {
  try
  { // Create the system.
    
    MultibodySystem         system;
    SimbodyMatterSubsystem  matter(system);
    GeneralForceSubsystem   forces(system);
    Force::UniformGravity   gravity(forces, matter, Vec3(0, -9.8, 0));

    PowerMeasure<Real> powMeas(matter, matter);
    Measure::Zero zeroMeas(matter);
    Measure::Integrate workMeas(matter, powMeas, zeroMeas); 

    Body::Rigid pendulumBody(MassProperties(1.0, Vec3(0), Inertia(1)));
    pendulumBody.addDecoration(Transform(), DecorativeSphere(0.1));


    // Prescribed system.
    MobilizedBody::Pin pendulum(matter.Ground(), Transform(Vec3(0)), 
                                pendulumBody,    Transform(Vec3(0, 1, 0)));
    Motion::Sinusoid(pendulum, Motion::Position, Pi/8, 2*Pi, Pi/4); // amp, rate, phase
    MobilizedBody::Pin pendulum2(pendulum, Transform(Vec3(0)), 
                                 pendulumBody,    Transform(Vec3(0, 1, 0)));
    MobilizedBody::Pin pendulum3(pendulum2, Vec3(0),
                                 pendulumBody, Vec3(0,.5,0));
    Motion::Steady(pendulum3, 4*Pi); // rate
    Force::MobilityLinearSpring(forces, pendulum2, MobilizerUIndex(0),
        100, 0*(Pi/180));

    // Identical constrained system.
    MobilizedBody::Pin cpendulum(matter.Ground(), Transform(Vec3(2,0,0)), 
                                 pendulumBody,    Transform(Vec3(0, 1, 0)));
    Constraint::PrescribedMotion(matter, 
                                 new Function::Sinusoid(Pi/8,2*Pi,Pi/4), //amp,rate,phase
                                 cpendulum, MobilizerQIndex(0));
    MobilizedBody::Pin cpendulum2(cpendulum, Transform(Vec3(0)), 
                                  pendulumBody, Transform(Vec3(0, 1, 0)));
    MobilizedBody::Pin cpendulum3(cpendulum2, Vec3(0),
                                 pendulumBody, Vec3(0,.5,0));
    Constraint::ConstantSpeed(cpendulum3, 4*Pi);
    Force::MobilityLinearSpring(forces, cpendulum2, MobilizerUIndex(0),
        100, 0*(Pi/180));

    Constraint::Rod(pendulum3, cpendulum3, RodLength);

    // Identical mixed system 1.
    MobilizedBody::Pin m1pendulum(matter.Ground(), Transform(Vec3(4,0,0)), 
                                  pendulumBody,    Transform(Vec3(0, 1, 0)));
    Motion::Sinusoid(m1pendulum, Motion::Position, Pi/8, 2*Pi, Pi/4); // amp, rate, phase
    MobilizedBody::Pin m1pendulum2(m1pendulum, Transform(Vec3(0)), 
                                   pendulumBody, Transform(Vec3(0, 1, 0)));
    MobilizedBody::Pin m1pendulum3(m1pendulum2, Vec3(0),
                                   pendulumBody, Vec3(0,.5,0));
    Constraint::ConstantSpeed(m1pendulum3, 4*Pi);
    Force::MobilityLinearSpring(forces, m1pendulum2, MobilizerUIndex(0),
        100, 0*(Pi/180));


    // Identical mixed system 2.
    MobilizedBody::Pin m2pendulum(matter.Ground(), Transform(Vec3(6,0,0)), 
                                 pendulumBody,    Transform(Vec3(0, 1, 0)));
    Constraint::PrescribedMotion(matter, 
                                 new Function::Sinusoid(Pi/8,2*Pi,Pi/4), //amp,rate,phase
                                 m2pendulum, MobilizerQIndex(0));
    MobilizedBody::Pin m2pendulum2(m2pendulum, Transform(Vec3(0)), 
                                   pendulumBody, Transform(Vec3(0, 1, 0)));
    MobilizedBody::Pin m2pendulum3(m2pendulum2, Vec3(0),
                                   pendulumBody, Vec3(0,.5,0));
    Motion::Steady(m2pendulum3, 4*Pi); // rat
    Force::MobilityLinearSpring(forces, m2pendulum2, MobilizerUIndex(0),
        100, 0*(Pi/180));

    Constraint::Rod(m1pendulum3, m2pendulum3, RodLength);


    Visualizer viz(system);
    system.addEventReporter(new Visualizer::Reporter(viz, 0.01));
    system.addEventReporter(new MyReporter(system, powMeas, workMeas, 0.01));

   
    // Initialize the system and state.
    
    system.realizeTopology();
    State state = system.getDefaultState();
    system.realize(state, Stage::Instance);
    const int nq = state.getNQ();
    const int nu = state.getNU();
    const int m  = state.getNMultipliers();

    viz.report(state);
    system.realize(state, Stage::Velocity);
    clog << "Default state -- hit ENTER\n";
    clog << "t=" << state.getTime() 
         << "\nq=" << state.getQ() 
         << "\nu=" << state.getU() 
         << "\nqerr=" << state.getQErr()
         << "\nuerr=" << state.getUErr()
         << endl;
    char c=getchar();

    state.setTime(0);
    system.realize(state, Stage::Time);


    clog << "After realize(Time) motion qerr=" 
         << matter.calcMotionErrors(state, Stage::Position) << "\n";
    system.prescribeQ(state);

    clog << "After prescribe() motion qerr=" 
         << matter.calcMotionErrors(state, Stage::Position) << "\n";

    //if (matter.prescribe(state, Stage::Position)) clog << "Some PresQ\n";
    //else clog << "NO PresQ\n";
    //clog << "after prescribe q=" << state.getQ() << "\n";
    system.realize(state, Stage::Position);

    system.projectQ(state, 1e-10);
    //Assembler asmb(system);
    //asmb.setAccuracy(1e-10).assemble(state);

    viz.report(state);
    clog << "After prescribe(Position) & project -- hit ENTER\n";
    clog << "t=" << state.getTime() 
         << "\nq=" << state.getQ() 
         << "\nu=" << state.getU() 
         << "\nqerr=" << state.getQErr()
         << endl;

    const int nfq = matter.getFreeQIndex(state).size();
    clog << "freeQ:     " << matter.getFreeQIndex(state) << "\n";

    Vector q = state.getQ(), packedQ(nfq), unpackedQ(nq);
    clog << "allQ         =" << q << "\n";
    matter.packFreeQ(state, q, packedQ);
    clog << "packedFreeQ  =" << packedQ << "\n";
    matter.unpackFreeQ(state, packedQ, unpackedQ);
    clog << "unpackedFreeQ=" << unpackedQ << "\n";

    c=getchar();

    clog << "After realize(Position) motion uerr=" 
         << matter.calcMotionErrors(state, Stage::Velocity) << "\n";
    system.prescribeU(state);
    clog << "After prescribe() motion uerr=" 
         << matter.calcMotionErrors(state, Stage::Velocity) << "\n";

    system.realize(state, Stage::Velocity);
    system.projectU(state, 1e-10);
    viz.report(state);
    clog << "After prescribe(Velocity) & project -- hit ENTER\n";
    clog << "t=" << state.getTime() 
         << "\nq=" << state.getQ() 
         << "\nu=" << state.getU() 
         << "\nuerr=" << state.getUErr()
         << endl;

    const int nfu = matter.getFreeUIndex(state).size();
    clog << "freeU:     " << matter.getFreeUIndex(state) << "\n";

    Vector u = state.getU(), packedU(nfu), unpackedU(nu);
    clog << "allU         =" << u << "\n";
    matter.packFreeU(state, u, packedU);
    clog << "packedFreeU  =" << packedU << "\n";
    matter.unpackFreeU(state, packedU, unpackedU);
    clog << "unpackedFreeU=" << unpackedU << "\n";


    c=getchar();

    system.realize(state, Stage::Acceleration);
    clog << "After realize(Acceleration) motion udoterr=" 
         << matter.calcMotionErrors(state, Stage::Acceleration) << "\n";

    clog << "After realize(Acceleration) -- hit ENTER\n";
    clog << "t=" << state.getTime() 
         << "\nq=" << state.getQ()
         << "\nu=" << state.getU() 
         << "\nudot=" << state.getUDot() 
         << "\ntau=" << pendulum.getTauAsVector(state) << pendulum2.getTauAsVector(state) << pendulum3.getTauAsVector(state)
         << endl;

    Vector_<SpatialVec> reactionForces, reactionForcesFreebody;
    matter.calcMobilizerReactionForces(state, reactionForces);
    matter.calcMobilizerReactionForcesUsingFreebodyMethod(state, reactionForcesFreebody);

    clog << "reactions PA+z: " << reactionForces << endl;
    clog << "react freebody: " << reactionForcesFreebody << endl;
    clog << "diff=" << reactionForces-reactionForcesFreebody << "\n";
    SimTK_TEST_EQ_SIZE(reactionForces, reactionForcesFreebody, nu);

    clog << "tau=" << matter.getMotionMultipliers(state) << "\n";
    Vector motFrcs;
    matter.findMotionForces(state, motFrcs);
    clog << "motion frc=" << motFrcs << "\n";
    clog << "gen speeds=" << matter.getU(state) << "\n";
    clog << "motion pwr=" << matter.calcMotionPower(state) << "\n";

    clog << "lambda=" << matter.getConstraintMultipliers(state) << "\n";
    Vector_<SpatialVec> consBodyFrc;
    Vector consMobFrc;
    matter.findConstraintForces(state, consBodyFrc, consMobFrc);
    clog << "cons bfrc=" << consBodyFrc << "\n";
    clog << "cons mfrc=" << consMobFrc << "\n";
    clog << "cons pwr=" << matter.calcConstraintPower(state) << "\n";


    clog << "freeUDot:  " << matter.getFreeUDotIndex(state) << "\n";
    clog << "knownUDot: " << matter.getKnownUDotIndex(state) << "\n";

    Matrix GMInvGt_r;
    matter.calcProjectedMInv(state, GMInvGt_r);

    Matrix G, M, Minv_r;
    matter.calcG(state, G);
    matter.calcM(state, M);
    matter.calcMInv(state, Minv_r);
    Matrix Minv = M.invert();

    const Array_<UIndex>& freeUDot = matter.getFreeUDotIndex(state);
    const int nfudot = freeUDot.size();
    Matrix Gr(m,nfudot), Mr(nfudot,nfudot);

    for (int i=0; i < nfu; ++i) {
        Gr(i) = G(freeUDot[i]);
        matter.packFreeU(state, M(freeUDot[i]), Mr(i));
    }

    cout << std::fixed;
    cout << "G=" << G;
    cout << "Gr=" << Gr;
    cout << "M=" <<  M;
    cout << "Mr=" <<  Mr;

    cout << "inv(M) =" << Minv;
    cout << "Minv_r =" << Minv_r;
    cout << "inv(Mr)=" << Mr.invert();

    clog << "GMInvGt_r     =" << GMInvGt_r;
    clog << "GMInv_rGt     =" << G*Minv_r*~G;
    clog << "Gr inv(Mr) ~Gr=" << Gr*Mr.invert()*~Gr;
    clog << "GMInvGt       =" << G*Minv*~G;


    c=getchar();

    //pendulum.setOneU(state, 0, 1.0);

    
    // Simulate it.


    //ExplicitEulerIntegrator integ(system);
    //CPodesIntegrator integ(system);
    //RungeKutta3Integrator integ(system);
    //VerletIntegrator integ(system);
    RungeKuttaMersonIntegrator integ(system);
    //RungeKuttaFeldbergIntegrator integ(system);
    //integ.setAllowInterpolation(false);
    //integ.setProjectInterpolatedStates(false);
    //integ.setMinimumStepSize(1e-1);
    integ.setAccuracy(1e-2);
    //integ.setConstraintTolerance(1e-3);
    TimeStepper ts(system, integ);
    ts.initialize(state);
    ts.stepTo(10.0);

  } catch (const std::exception& e) {
    cerr << "EXCEPTION THROWN: " << e.what() << "\n";
    exit(1);

  } catch (...) {
    cerr << "UNKNOWN EXCEPTION THROWN\n";
    exit(1);
  }

    return 0;
}