Simbody  3.4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Assembler.h
Go to the documentation of this file.
1 #ifndef SimTK_SIMBODY_ASSEMBLER_H_
2 #define SimTK_SIMBODY_ASSEMBLER_H_
3 
4 /* -------------------------------------------------------------------------- *
5  * Simbody(tm) *
6  * -------------------------------------------------------------------------- *
7  * This is part of the SimTK biosimulation toolkit originating from *
8  * Simbios, the NIH National Center for Physics-Based Simulation of *
9  * Biological Structures at Stanford, funded under the NIH Roadmap for *
10  * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
11  * *
12  * Portions copyright (c) 2010-12 Stanford University and the Authors. *
13  * Authors: Michael Sherman *
14  * Contributors: *
15  * *
16  * Licensed under the Apache License, Version 2.0 (the "License"); you may *
17  * not use this file except in compliance with the License. You may obtain a *
18  * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
19  * *
20  * Unless required by applicable law or agreed to in writing, software *
21  * distributed under the License is distributed on an "AS IS" BASIS, *
22  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
23  * See the License for the specific language governing permissions and *
24  * limitations under the License. *
25  * -------------------------------------------------------------------------- */
26 
27 #include "SimTKcommon.h"
31 
32 #include <set>
33 #include <map>
34 #include <cassert>
35 #include <cmath>
36 
37 namespace SimTK {
38 
39 SimTK_DEFINE_UNIQUE_INDEX_TYPE(AssemblyConditionIndex);
40 
41 class AssemblyCondition;
42 
149  typedef std::set<MobilizedBodyIndex> LockedMobilizers;
150  typedef std::set<MobilizerQIndex> QSet;
151  typedef std::map<MobilizedBodyIndex, QSet> LockedQs;
152  typedef std::map<MobilizerQIndex, Vec2> QRanges;
153  typedef std::map<MobilizedBodyIndex, QRanges> RestrictedQs;
154 public:
155 
159 
163 class AssembleFailed;
167 class TrackFailed;
168 
186 explicit Assembler(const MultibodySystem& system);
187 
198  SimTK_ERRCHK1_ALWAYS(0 <= tolerance,
199  "Assembler::setTolerance()", "The requested error tolerance %g"
200  " is illegal; we require 0 <= tolerance, with 0 indicating that"
201  " the default tolerance (accuracy/10) is to be used.", tolerance);
202  this->tolerance = tolerance;
203  return *this;
204 }
210  return tolerance > 0 ? tolerance
211  : (accuracy > 0 ? accuracy/10 : Real(0.1)/OODefaultAccuracy);
212 }
213 
223 Assembler& setAccuracy(Real accuracy=0) {
224  SimTK_ERRCHK2_ALWAYS(0 <= accuracy && accuracy < 1,
225  "Assembler::setAccuracy()", "The requested accuracy %g is illegal;"
226  " we require 0 <= accuracy < 1, with 0 indicating that the default"
227  " accuracy (%g) is to be used.", Real(1)/OODefaultAccuracy, accuracy);
228  this->accuracy = accuracy;
229  return *this;
230 }
233 Real getAccuracyInUse() const
234 { return accuracy > 0 ? accuracy : Real(1)/OODefaultAccuracy; }
235 
236 
243 Assembler& setSystemConstraintsWeight(Real weight)
244 { assert(systemConstraints.isValid());
245  setAssemblyConditionWeight(systemConstraints,weight);
246  return *this; }
247 
251 Real getSystemConstraintsWeight() const
252 { assert(systemConstraints.isValid());
253  return getAssemblyConditionWeight(systemConstraints); }
254 
261 Assembler& setAssemblyConditionWeight(AssemblyConditionIndex condition,
262  Real weight) {
263  SimTK_INDEXCHECK_ALWAYS(condition, conditions.size(),
264  "Assembler::setAssemblyConditionWeight()");
265  SimTK_ERRCHK1_ALWAYS(weight >= 0, "Assembler::setAssemblyConditionWeight()",
266  "Illegal weight %g; weight must be nonnegative.", weight);
267  uninitialize();
268  weights[condition] = weight;
269  return *this;
270 }
271 
278 Real getAssemblyConditionWeight(AssemblyConditionIndex condition) const {
279  SimTK_INDEXCHECK_ALWAYS(condition, conditions.size(),
280  "Assembler::getAssemblyConditionWeight()");
281  return weights[condition];
282 }
283 
288 AssemblyConditionIndex
289  adoptAssemblyError(AssemblyCondition* p);
298 AssemblyConditionIndex
299  adoptAssemblyGoal(AssemblyCondition* p, Real weight=1);
300 
301 
308  uninitialize();
309  getMatterSubsystem().convertToEulerAngles(state, internalState);
310  system.realizeModel(internalState);
311  return *this;
312 }
319 void initialize() const;
322 void initialize(const State& state)
323 { setInternalState(state); initialize(); }
330 
337 Real assemble();
338 
347 Real track(Real frameTime = -1);
348 
355 Real assemble(State& state) {
356  setInternalState(state);
357  Real achievedCost = assemble(); // throws if it fails
358  updateFromInternalState(state);
359  return achievedCost;
360 }
361 
362 
366 Real calcCurrentGoal() const;
375 Real calcCurrentErrorNorm() const;
376 
377 
382 void updateFromInternalState(State& state) const {
383  system.realizeModel(state); // allocates q's if they haven't been yet
384  if (!getMatterSubsystem().getUseEulerAngles(state)) {
385  State tempState;
386  getMatterSubsystem().convertToQuaternions(getInternalState(),
387  tempState);
388  state.updQ() = tempState.getQ();
389  } else
390  state.updQ() = getInternalState().getQ();
391 }
401 
405 void lockMobilizer(MobilizedBodyIndex mbx)
406 { uninitialize(); userLockedMobilizers.insert(mbx); }
412 void unlockMobilizer(MobilizedBodyIndex mbx)
413 { uninitialize(); userLockedMobilizers.erase(mbx); }
414 
427 { uninitialize(); userLockedQs[mbx].insert(qx); }
428 
433 void unlockQ(MobilizedBodyIndex mbx, MobilizerQIndex qx)
434 { LockedQs::iterator p = userLockedQs.find(mbx);
435  if (p == userLockedQs.end()) return;
436  QSet& qs = p->second;
437  if (qs.erase(qx)) { // returns 0 if nothing erased
438  uninitialize();
439  if (qs.empty())
440  userLockedQs.erase(p); // remove the whole mobilized body
441  }
442 }
443 
449 void restrictQ(MobilizedBodyIndex mbx, MobilizerQIndex qx,
450  Real lowerBound, Real upperBound)
451 { SimTK_ERRCHK2_ALWAYS(lowerBound <= upperBound, "Assembler::restrictQ()",
452  "The given range [%g,%g] is illegal because the lower bound is"
453  " greater than the upper bound.", lowerBound, upperBound);
454  if (lowerBound == -Infinity && upperBound == Infinity)
455  { unrestrictQ(mbx,qx); return; }
456  uninitialize();
457  userRestrictedQs[mbx][qx] = Vec2(lowerBound,upperBound);
458 }
459 
460 
465 void unrestrictQ(MobilizedBodyIndex mbx, MobilizerQIndex qx)
466 { RestrictedQs::iterator p = userRestrictedQs.find(mbx);
467  if (p == userRestrictedQs.end()) return;
468  QRanges& qranges = p->second;
469  if (qranges.erase(qx)) { // returns 0 if nothing erased
470  uninitialize();
471  if (qranges.empty())
472  userRestrictedQs.erase(p); // remove the whole mobilized body
473  }
474 }
487 int getNumGoalEvals() const;
489 int getNumErrorEvals() const;
491 int getNumGoalGradientEvals() const;
493 int getNumErrorJacobianEvals() const;
496 int getNumAssemblySteps() const;
499 int getNumInitializations() const;
503 void resetStats() const;
511 
514 void setForceNumericalGradient(bool yesno)
515 { forceNumericalGradient = yesno; }
518 void setForceNumericalJacobian(bool yesno)
519 { forceNumericalJacobian = yesno; }
520 
526 void setUseRMSErrorNorm(bool yesno)
527 { useRMSErrorNorm = yesno; }
531 bool isUsingRMSErrorNorm() const {return useRMSErrorNorm;}
532 
537 void uninitialize() const;
540 bool isInitialized() const {return alreadyInitialized;}
541 
548 const State& getInternalState() const {return internalState;}
549 
553 void addReporter(const EventReporter& reporter) {
554  reporters.push_back(&reporter);
555 }
556 
560 int getNumFreeQs() const
561 { return freeQ2Q.size(); }
562 
566 QIndex getQIndexOfFreeQ(FreeQIndex freeQIndex) const
567 { return freeQ2Q[freeQIndex]; }
568 
573 FreeQIndex getFreeQIndexOfQ(QIndex qx) const
574 { return q2FreeQ[qx]; }
575 
578 Vec2 getFreeQBounds(FreeQIndex freeQIndex) const {
579  if (!lower.size()) return Vec2(-Infinity, Infinity);
580  else return Vec2(lower[freeQIndex], upper[freeQIndex]);
581 }
582 
586 const MultibodySystem& getMultibodySystem() const
587 { return system; }
590 const SimbodyMatterSubsystem& getMatterSubsystem() const
591 { return system.getMatterSubsystem(); }
596 ~Assembler();
597 
598 
599 
600 //------------------------------------------------------------------------------
601  private: // methods
602 //------------------------------------------------------------------------------
603 void setInternalStateFromFreeQs(const Vector& freeQs) {
604  assert(freeQs.size() == getNumFreeQs());
605  Vector& q = internalState.updQ();
606  for (FreeQIndex fx(0); fx < getNumFreeQs(); ++fx)
607  q[getQIndexOfFreeQ(fx)] = freeQs[fx];
608  system.realize(internalState, Stage::Position);
609 }
610 
611 Vector getFreeQsFromInternalState() const {
612  Vector freeQs(getNumFreeQs());
613  const Vector& q = internalState.getQ();
614  for (FreeQIndex fx(0); fx < getNumFreeQs(); ++fx)
615  freeQs[fx] = q[getQIndexOfFreeQ(fx)];
616  return freeQs;
617 }
618 
619 void reinitializeWithExtraQsLocked
620  (const Array_<QIndex>& toBeLocked) const;
621 
622 
623 
624 //------------------------------------------------------------------------------
625  private: // data members
626 //------------------------------------------------------------------------------
627 const MultibodySystem& system;
628 Array_<const EventReporter*> reporters; // just references; don't delete
629 
630 // These members affect the behavior of the assembly algorithm.
631 static const int OODefaultAccuracy = 1000; // 1/accuracy if acc==0
632 Real accuracy; // 0 means use 1/OODefaultAccuracy
633 Real tolerance; // 0 means use accuracy/10
634 bool forceNumericalGradient; // ignore analytic gradient methods
635 bool forceNumericalJacobian; // ignore analytic Jacobian methods
636 bool useRMSErrorNorm; // what norm defines success?
637 
638 // Changes to any of these data members set isInitialized()=false.
639 State internalState;
640 
641 // These are the mobilizers that were set in lockMobilizer(). They are
642 // separate from those involved in individually-locked q's.
643 LockedMobilizers userLockedMobilizers;
644 // These are locks placed on individual q's; they are independent of the
645 // locked mobilizer settings.
646 LockedQs userLockedQs;
647 // These are range restrictions placed on individual q's.
648 RestrictedQs userRestrictedQs;
649 
650 // These are (condition,weight) pairs with weight==Infinity meaning
651 // constraint; weight==0 meaning currently ignored; and any other
652 // positive weight meaning a goal.
653 Array_<AssemblyCondition*,AssemblyConditionIndex>
654  conditions;
655 Array_<Real,AssemblyConditionIndex> weights;
656 
657 // We always have an assembly condition for the Constraints which are
658 // enabled in the System; this is the index which can be used to
659 // retrieve that condition. The default weight is Infinity.
660 AssemblyConditionIndex systemConstraints;
661 
662 
663 // These are filled in when the Assembler is initialized.
664 mutable bool alreadyInitialized;
665 
666 // These are extra q's we removed for numerical reasons.
667 mutable Array_<QIndex> extraQsLocked;
668 
669 // These represent restrictions on the independent variables (q's).
670 mutable std::set<QIndex> lockedQs;
671 mutable Array_<FreeQIndex,QIndex> q2FreeQ; // nq of these
672 mutable Array_<QIndex,FreeQIndex> freeQ2Q; // nfreeQ of these
673 // 0 length if no bounds; otherwise, index by FreeQIndex.
674 mutable Vector lower, upper;
675 
676 // These represent the active assembly conditions.
677 mutable Array_<AssemblyConditionIndex> errors;
678 mutable Array_<int> nTermsPerError;
679 mutable Array_<AssemblyConditionIndex> goals;
680 
681 class AssemblerSystem; // local class
682 mutable AssemblerSystem* asmSys;
683 mutable Optimizer* optimizer;
684 
685 mutable int nAssemblySteps; // count assemble() and track() calls
686 mutable int nInitializations; // # times we had to reinitialize
687 
688 friend class AssemblerSystem;
689 };
690 
691 
692 
693 //------------------------------------------------------------------------------
694 // ASSEMBLY CONDITION
695 //------------------------------------------------------------------------------
703 public:
704 
707 explicit AssemblyCondition(const String& name)
708 : name(name), assembler(0) {}
709 
711 virtual ~AssemblyCondition() {}
712 
719 virtual int initializeCondition() const {return 0;}
720 
723 virtual void uninitializeCondition() const {}
724 
733 virtual int calcErrors(const State& state, Vector& err) const
734 { return -1; }
735 
745 virtual int calcErrorJacobian(const State& state, Matrix& jacobian) const
746 { return -1; }
747 
755 virtual int getNumErrors(const State& state) const
756 { Vector err;
757  const int status = calcErrors(state, err);
758  if (status == 0)
759  return err.size();
760  SimTK_ERRCHK1_ALWAYS(status != -1, "AssemblyCondition::getNumErrors()",
761  "The default implementation of getNumErrors() depends on"
762  " calcErrors() but that method was not implemented for assembly"
763  " condition '%s'.", name.c_str());
764  SimTK_ERRCHK2_ALWAYS(status == 0, "AssemblyCondition::getNumErrors()",
765  "The default implementation of getNumErrors() uses calcErrors()"
766  " which returned status %d (assembly condition '%s').",
767  status, name.c_str());
768  return -1; // NOTREACHED
769 }
770 
775 virtual int calcGoal(const State& state, Real& goal) const
776 { static Vector err;
777  const int status = calcErrors(state, err);
778  if (status == 0)
779  { goal = err.normSqr() / std::max(1,err.size());
780  return 0; }
781  SimTK_ERRCHK1_ALWAYS(status != -1, "AssemblyCondition::calcGoal()",
782  "The default implementation of calcGoal() depends on calcErrors()"
783  " but that method was not implemented for assembly condition '%s'.",
784  name.c_str());
785  SimTK_ERRCHK2_ALWAYS(status == 0, "AssemblyCondition::calcGoal()",
786  "The default implementation of calcGoal() uses calcErrors() which"
787  " returned status %d (assembly condition '%s').",
788  status, name.c_str());
789  return -1; // NOTREACHED
790 }
791 
798 virtual int calcGoalGradient(const State& state, Vector& gradient) const
799 { return -1; }
800 
802 const char* getName() const {return name.c_str();}
803 
806 bool isInAssembler() const {return assembler != 0;}
810 const Assembler& getAssembler() const
811 { assert(assembler); return *assembler;}
815 AssemblyConditionIndex getAssemblyConditionIndex() const
816 { return myAssemblyConditionIndex; }
817 
818 //------------------------------------------------------------------------------
819  protected:
820 //------------------------------------------------------------------------------
821 // These are useful when writing concrete AssemblyConditions.
822 
825 int getNumFreeQs() const {return getAssembler().getNumFreeQs();}
829 QIndex getQIndexOfFreeQ(Assembler::FreeQIndex fx) const
830 { return getAssembler().getQIndexOfFreeQ(fx); }
834 Assembler::FreeQIndex getFreeQIndexOfQ(QIndex qx) const
835 { return getAssembler().getFreeQIndexOfQ(qx); }
837 const MultibodySystem& getMultibodySystem() const
838 { return getAssembler().getMultibodySystem(); }
841 const SimbodyMatterSubsystem& getMatterSubsystem() const
842 { return getMultibodySystem().getMatterSubsystem(); }
843 
846 void initializeAssembler() const {
847  // The Assembler will in turn invoke initializeCondition().
848  if (isInAssembler()) getAssembler().initialize();
849  else initializeCondition();
850 }
851 
855 void uninitializeAssembler() const {
856  // The Assembler will in turn invoke uninitializeCondition().
857  if (isInAssembler()) getAssembler().uninitialize();
858  else uninitializeCondition();
859 }
860 
861 //------------------------------------------------------------------------------
862  private:
863 //------------------------------------------------------------------------------
864 // This method is used by the Assembler when the AssemblyCondition object
865 // is adopted.
866 friend class Assembler;
867 void setAssembler(const Assembler& assembler, AssemblyConditionIndex acx) {
868  assert(!this->assembler);
869  this->assembler = &assembler;
870  this->myAssemblyConditionIndex = acx;
871 }
872 
873 String name; // assembly condition name
874 const Assembler* assembler;
875 AssemblyConditionIndex myAssemblyConditionIndex;
876 };
877 
878 
879 
880 //------------------------------------------------------------------------------
881 // Q VALUE
882 //------------------------------------------------------------------------------
886 class QValue : public AssemblyCondition {
887 public:
892  Real value)
893  : AssemblyCondition("QValue"),
894  mobodIndex(mbx), qIndex(qx), value(value) {}
895 
898  Real getValue() const {return value;}
901  void setValue(Real newValue) {value=newValue;}
902 
903  // For constraint:
904  int getNumEquations(const State&) const {return 1;}
905  int calcErrors(const State& state, Vector& error) const {
906  const SimbodyMatterSubsystem& matter = getMatterSubsystem();
907  const MobilizedBody& mobod = matter.getMobilizedBody(mobodIndex);
908  error.resize(1);
909  error[0] = mobod.getOneQ(state, qIndex) - value;
910  return 0;
911  }
912  // Error jacobian is a zero-row except for a 1 in this q's entry (if
913  // this q is free).
914  int calcErrorJacobian(const State& state, Matrix& J) const {
915  const SimbodyMatterSubsystem& matter = getMatterSubsystem();
916  const MobilizedBody& mobod = matter.getMobilizedBody(mobodIndex);
917  J.resize(1, getNumFreeQs());
918  J = 0; // will have at most one non-zero
919 
920  // Find the FreeQIndex corresponding to this q.
921  const QIndex thisIx = QIndex(mobod.getFirstQIndex(state)+qIndex);
922  const Assembler::FreeQIndex thisFreeIx = getFreeQIndexOfQ(thisIx);
923 
924  // If this q isn't free then there is no way to affect the error
925  // so the Jacobian stays all-zero.
926  if (thisFreeIx.isValid())
927  J(0,thisFreeIx) = 1;
928 
929  return 0;
930  }
931 
932  // For goal: goal = (q-value)^2 / 2 (the /2 is for gradient beauty)
933  int calcGoal(const State& state, Real& goal) const {
934  const SimbodyMatterSubsystem& matter = getMatterSubsystem();
935  const MobilizedBody& mobod = matter.getMobilizedBody(mobodIndex);
936  goal = square(mobod.getOneQ(state, qIndex) - value) / 2;
937  return 0;
938  }
939  // Return a gradient with only this q's entry non-zero (if
940  // this q is free).
941  int calcGoalGradient(const State& state, Vector& grad) const {
942  const SimbodyMatterSubsystem& matter = getMatterSubsystem();
943  const MobilizedBody& mobod = matter.getMobilizedBody(mobodIndex);
944  grad.resize(getNumFreeQs());
945  grad = 0; // will have at most one non-zero
946 
947  // Find the FreeQIndex corresponding to this q.
948  const QIndex thisIx = QIndex(mobod.getFirstQIndex(state)+qIndex);
949  const Assembler::FreeQIndex thisFreeIx = getFreeQIndexOfQ(thisIx);
950 
951  // If this q isn't free then there is no way to affect the goal
952  // so the gradient stays all-zero.
953  if (thisFreeIx.isValid())
954  grad[thisFreeIx] = mobod.getOneQ(state, qIndex) - value;
955 
956  return 0;
957  }
958 
959 private:
960  MobilizedBodyIndex mobodIndex;
961  MobilizerQIndex qIndex;
962  Real value;
963 };
964 
965 
966 
967 //------------------------------------------------------------------------------
968 // MARKERS
969 //------------------------------------------------------------------------------
1013 
1014 // This is a private class used in the implementation below but not
1015 // accessible through the API.
1016 struct Marker {
1017  Marker(const String& name, MobilizedBodyIndex bodyB,
1018  const Vec3& markerInB, Real weight = 1)
1019  : name(name), bodyB(bodyB), markerInB(markerInB), weight(weight)
1020  { assert(weight >= 0); }
1021 
1022  Marker(MobilizedBodyIndex bodyB, const Vec3& markerInB, Real weight=1)
1023  : name(""), bodyB(bodyB), markerInB(markerInB), weight(weight)
1024  { assert(weight >= 0); }
1025 
1026  String name;
1027  MobilizedBodyIndex bodyB;
1028  Vec3 markerInB;
1029  Real weight;
1030 };
1031 
1032 public:
1033 
1038 
1039 
1040 
1041 //------------------------------------------------------------------------------
1047 
1051 Markers() : AssemblyCondition("Markers") {}
1052 
1072 MarkerIx addMarker(const String& name, MobilizedBodyIndex bodyB,
1073  const Vec3& markerInB, Real weight=1)
1074 { SimTK_ERRCHK1_ALWAYS(isFinite(weight) && weight >= 0,
1075  "Markers::addMarker()", "Illegal marker weight %g.", weight);
1076  uninitializeAssembler();
1077  // Forget any previously-established observation/marker correspondence.
1078  observation2marker.clear(); marker2observation.clear();
1079  observations.clear();
1080  const MarkerIx ix(markers.size());
1081  String nm = String::trimWhiteSpace(name);
1082  if (nm.empty())
1083  nm = String("_UNNAMED_") + String(ix);
1084 
1085  std::pair< std::map<String,MarkerIx>::iterator, bool >
1086  found = markersByName.insert(std::make_pair(nm,ix));
1087  SimTK_ERRCHK2_ALWAYS(found.second, // true if insertion was done
1088  "Markers::addMarker()",
1089  "Marker name '%s' was already use for Marker %d.",
1090  nm.c_str(), (int)found.first->second);
1091 
1092  markers.push_back(Marker(nm,bodyB,markerInB,weight));
1093  return ix;
1094 }
1095 
1100 MarkerIx addMarker(MobilizedBodyIndex bodyB, const Vec3& markerInB,
1101  Real weight=1)
1102 { return addMarker("", bodyB, markerInB, weight); }
1103 
1104 
1125 void defineObservationOrder(const Array_<MarkerIx>& observationOrder) {
1126  uninitializeAssembler();
1127  if (observationOrder.empty()) {
1128  observation2marker.resize(markers.size());
1129  for (MarkerIx mx(0); mx < markers.size(); ++mx)
1130  observation2marker[ObservationIx(mx)] = mx;
1131  } else
1132  observation2marker = observationOrder;
1133  marker2observation.clear();
1134  // We might need to grow this more, but this is an OK starting guess.
1135  marker2observation.resize(observation2marker.size()); // all invalid
1136  for (ObservationIx ox(0); ox < observation2marker.size(); ++ox) {
1137  const MarkerIx mx = observation2marker[ox];
1138  if (!mx.isValid()) continue;
1139 
1140  if (marker2observation.size() <= mx)
1141  marker2observation.resize(mx+1);
1142  SimTK_ERRCHK4_ALWAYS(!marker2observation[mx].isValid(),
1143  "Markers::defineObservationOrder()",
1144  "An attempt was made to associate Marker %d (%s) with"
1145  " Observations %d and %d; only one Observation per Marker"
1146  " is permitted.",
1147  (int)mx, getMarkerName(mx).c_str(),
1148  (int)marker2observation[mx], (int)ox);
1149 
1150  marker2observation[mx] = ox;
1151  }
1152  // Make room for marker observations.
1153  observations.clear();
1154  observations.resize(observation2marker.size(),Vec3(NaN));
1155 }
1156 
1162 void defineObservationOrder(const Array_<String>& observationOrder)
1163 { Array_<MarkerIx> markerIxs(observationOrder.size());
1164  for (ObservationIx ox(0); ox < observationOrder.size(); ++ox)
1165  markerIxs[ox] = getMarkerIx(observationOrder[ox]);
1166  defineObservationOrder(markerIxs); }
1167 
1169 // no copy required
1170 void defineObservationOrder(const std::vector<String>& observationOrder)
1171 { defineObservationOrder(ArrayViewConst_<String>(observationOrder)); }
1172 
1173 
1175 // must copy
1176 void defineObservationOrder(const Array_<std::string>& observationOrder)
1177 { const Array_<String> observations(observationOrder); // copy
1178  defineObservationOrder(observations); }
1179 
1181 // must copy
1182 void defineObservationOrder(const std::vector<std::string>& observationOrder)
1183 { const Array_<String> observations(observationOrder); // copy
1184  defineObservationOrder(observations); }
1185 
1187 void defineObservationOrder(int n, const char* const observationOrder[])
1188 { Array_<MarkerIx> markerIxs(n);
1189  for (ObservationIx ox(0); ox < n; ++ox)
1190  markerIxs[ox] = getMarkerIx(String(observationOrder[ox]));
1191  defineObservationOrder(markerIxs); }
1196 //------------------------------------------------------------------------------
1203 
1206 int getNumMarkers() const {return markers.size();}
1207 
1211 const String& getMarkerName(MarkerIx ix)
1212 { return markers[ix].name; }
1216 const MarkerIx getMarkerIx(const String& name)
1217 { std::map<String,MarkerIx>::const_iterator p = markersByName.find(name);
1218  return p == markersByName.end() ? MarkerIx() : p->second; }
1219 
1222 Real getMarkerWeight(MarkerIx mx)
1223 { return markers[mx].weight; }
1224 
1226 MobilizedBodyIndex getMarkerBody(MarkerIx mx) const
1227 { return markers[mx].bodyB; }
1228 
1230 const Vec3& getMarkerStation(MarkerIx mx) const
1231 { return markers[mx].markerInB; }
1232 
1238 int getNumObservations() const {return observation2marker.size();}
1239 
1245 ObservationIx getObservationIxForMarker(MarkerIx mx) const
1246 { return marker2observation[mx]; }
1247 
1250 bool hasObservation(MarkerIx mx) const
1251 { return getObservationIxForMarker(mx).isValid(); }
1252 
1258 MarkerIx getMarkerIxForObservation(ObservationIx ox) const
1259 { return observation2marker[ox]; }
1260 
1263 bool hasMarker(ObservationIx ox) const
1264 { return getMarkerIxForObservation(ox).isValid();}
1265 
1271  static const Array_<MarkerIx> empty;
1272  SimTK_ERRCHK_ALWAYS(isInAssembler(), "Markers::getMarkersOnBody()",
1273  "This method can't be called until the Markers object has been"
1274  " adopted by an Assembler.");
1275  initializeAssembler();
1276  PerBodyMarkers::const_iterator bodyp = bodiesWithMarkers.find(mbx);
1277  return bodyp == bodiesWithMarkers.end() ? empty : bodyp->second;
1278 }
1283 //------------------------------------------------------------------------------
1289 
1293 void moveOneObservation(ObservationIx ox, const Vec3& observation)
1294 { SimTK_ERRCHK_ALWAYS(!observations.empty(), "Assembler::moveOneObservation()",
1295  "There are currently no observations defined. Either the Assembler"
1296  " needs to be initialized to get the default observation order, or you"
1297  " should call defineObservationOrder() explicitly.");
1298  SimTK_ERRCHK2_ALWAYS(ox.isValid() && ox < observations.size(),
1299  "Assembler::moveOneObservation()", "ObservationIx %d is invalid or"
1300  " out of range; there are %d observations currently defined. Use"
1301  " defineObservationOrder() to specify the set of observations and how"
1302  " they correspond to markers.",
1303  (int)ox, (int)observations.size());
1304  observations[ox] = observation;
1305 }
1306 
1316 void moveAllObservations(const Array_<Vec3>& observations)
1317 { SimTK_ERRCHK2_ALWAYS((int)observations.size() == (int)observation2marker.size(),
1318  "Markers::moveAllObservations()",
1319  "Number of observations provided (%d) differs from the number of"
1320  " observations (%d) last defined with defineObservationOrder().",
1321  observations.size(), observation2marker.size());
1322  this->observations = observations; }
1323 
1333 void changeMarkerWeight(MarkerIx mx, Real weight) {
1334  SimTK_ERRCHK1_ALWAYS(isFinite(weight) && weight >= 0,
1335  "Markers::changeMarkerWeight()", "Illegal marker weight %g.", weight);
1336 
1337  Marker& marker = markers[mx];
1338  if (marker.weight == weight)
1339  return;
1340 
1341  if (marker.weight == 0 || weight == 0)
1342  uninitializeAssembler(); // qualitative change
1343 
1344  marker.weight = weight;
1345 }
1346 
1351 const Vec3& getObservation(ObservationIx ox) const {return observations[ox];}
1358 const Array_<Vec3,ObservationIx>& getAllObservations() const
1359 { return observations; }
1360 
1364 Vec3 findCurrentMarkerLocation(MarkerIx mx) const;
1365 
1375 Real findCurrentMarkerError(MarkerIx mx) const
1376 { return std::sqrt(findCurrentMarkerErrorSquared(mx)); }
1377 
1386  const ObservationIx ox = getObservationIxForMarker(mx);
1387  if (!ox.isValid()) return 0; // no observation for this marker
1388  const Vec3& loc = getObservation(ox);
1389  if (!loc.isFinite()) return 0; // NaN in observation; error is ignored
1390  return (findCurrentMarkerLocation(mx) - loc).normSqr();
1391 }
1396 //------------------------------------------------------------------------------
1400 int calcErrors(const State& state, Vector& err) const;
1401 int calcErrorJacobian(const State& state, Matrix& jacobian) const;
1402 int getNumErrors(const State& state) const;
1403 int calcGoal(const State& state, Real& goal) const;
1404 int calcGoalGradient(const State& state, Vector& grad) const;
1405 int initializeCondition() const;
1406 void uninitializeCondition() const;
1409 //------------------------------------------------------------------------------
1410  private:
1411 //------------------------------------------------------------------------------
1412 const Marker& getMarker(MarkerIx i) const {return markers[i];}
1413 Marker& updMarker(MarkerIx i) {uninitializeAssembler(); return markers[i];}
1414 
1415  // data members
1416 
1417 // Marker definition. Any change here except a quantitative change to the
1418 // marker's weight uninitializes the Assembler.
1419 Array_<Marker,MarkerIx> markers;
1420 std::map<String,MarkerIx> markersByName;
1421 
1422 // Observation-marker corresondence specification. Any change here
1423 // uninitializes the Assembler.
1424 Array_<MarkerIx,ObservationIx> observation2marker;
1425 
1426 // For convience in mapping from a marker to its corresponding observation.
1427 // ObservationIx will be invalid if a particular marker has no associated
1428 // observation.
1429 Array_<ObservationIx,MarkerIx> marker2observation;
1430 
1431 // This is the current set of marker location observations, one per entry in
1432 // the observation2marker array. Changing the values here does not uninitialize
1433 // the Assembler.
1434 Array_<Vec3,ObservationIx> observations;
1435 
1436 // After initialize, this groups the markers by body and weeds out
1437 // any zero-weighted markers. TODO: skip low-weighted markers, at
1438 // least at the start of the assembly.
1439 typedef std::map<MobilizedBodyIndex,Array_<MarkerIx> > PerBodyMarkers;
1440 mutable PerBodyMarkers bodiesWithMarkers;
1441 };
1442 
1443 } // namespace SimTK
1444 
1445 #endif // SimTK_SIMBODY_ASSEMBLER_H_