-
Notifications
You must be signed in to change notification settings - Fork 377
Expand file tree
/
Copy pathPolynomialPathFitter.cpp
More file actions
1723 lines (1510 loc) · 73.7 KB
/
Copy pathPolynomialPathFitter.cpp
File metadata and controls
1723 lines (1510 loc) · 73.7 KB
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
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -------------------------------------------------------------------------- *
* OpenSim: PolynomialPathFitter.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2026 Stanford University and the Authors *
* Author(s): Nicholas Bianco *
* *
* 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. *
* -------------------------------------------------------------------------- */
#include "PolynomialPathFitter.h"
#include <OpenSim/Actuators/ModelOperators.h>
#include <OpenSim/Common/CommonUtilities.h>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/STOFileAdapter.h>
#include <OpenSim/Common/LatinHypercubeDesign.h>
#include <OpenSim/Common/MultivariatePolynomialFunction.h>
#include <OpenSim/Simulation/Control/PrescribedController.h>
#include <OpenSim/Simulation/Manager/Manager.h>
#include <atomic>
#include <future>
using namespace OpenSim;
namespace {
// Type alias for the moment arm map. The keys are the paths in the model
// and the values are vectors containing the (model) paths to coordinates on
// which the (wrapping) paths depend.
using MomentArmMap = std::unordered_map<std::string, std::vector<std::string>>;
// Type alias for the coordinate bounds and coordinate range maps. The keys are
// the coordinate paths in the model and the values are `SimTK::Vec2` objects
// containing the bounds or ranges for each coordinate.
using CoordinateMap = std::unordered_map<std::string, SimTK::Vec2>;
// A struct for containing validated settings based on the values provided by
// the user via the PolynomialPathFitter properties.
struct Settings {
bool useStepwiseRegression = false;
double momentArmTolerance = 1e-4;
double pathLengthTolerance = 1e-4;
int minimumPolynomialOrder = 2;
int maximumPolynomialOrder = 6;
int numParallelThreads = (int)std::thread::hardware_concurrency();
SimTK::Vec2 globalCoordinateSamplingBounds{-10.0, 10.0};
int numSamplesPerFrame = 25;
bool useStochasticEvolutionaryLHS = false;
bool includeMomentArmFunctions = false;
bool includeLengtheningSpeedFunction = false;
};
// Helper function to load the reference coordinate values trajectory and
// validate the model. The coordinate values table is modified to update the
// column labels based on the model coordinate paths, to update any
// coordinates dependent on `CoordinateCouplerConstraint`s, and to convert
// the coordinate values to radians if the "inDegrees" metadata flag is set
// to "yes".
TimeSeriesTable loadCoordinateValuesAndValidateModel(
const std::string& documentDir,
TableProcessor tableProcessor,
Model& model) {
const auto pathList = model.getComponentList<AbstractGeometryPath>();
int numPaths = (int)std::distance(pathList.begin(), pathList.end());
OPENSIM_THROW_IF(!numPaths, Exception,
"Expected the model to contain at least one AbstractGeometryPath, "
"but it does not.")
const auto fbPathList = model.getComponentList<FunctionBasedPath>();
int numFunctionBasedPaths = (int)std::distance(fbPathList.begin(),
fbPathList.end());
OPENSIM_THROW_IF(numFunctionBasedPaths, Exception,
"Expected the model to not contain any FunctionBasedPaths, but it "
"does. Please remove all FunctionBasedPaths from the model before "
"running the PolynomialPathFitter.")
// Load the coordinate values.
tableProcessor.append(TabOpConvertDegreesToRadians());
tableProcessor.append(TabOpUseAbsoluteStateNames());
tableProcessor.append(TabOpAppendCoupledCoordinateValues());
TimeSeriesTable values = tableProcessor.process(documentDir, &model);
log_info("Coordinate values table: {} columns, {} time points",
values.getNumColumns(), values.getNumRows());
// Remove any rows in the coordinate values table provided by the user that
// contain NaN values.
const auto& times = values.getIndependentColumn();
for (int i = 0; i < static_cast<int>(times.size()); ++i) {
if (SimTK::isNaN(values.getRowAtIndex(i).sum())) {
values.removeRow(times[i]);
log_info("NaN coordinate value detected at time {:1.2f} s, "
"removing row...", times[i]);
}
}
// Validate the coordinate values table
std::vector<std::string> jointsToWeld;
for (auto& coordinate : model.updComponentList<Coordinate>()) {
std::string valuePath = fmt::format("{}/value",
coordinate.getAbsolutePathString());
// If the coordinate is locked, but the user provided a column for the
// coordinate, then we unlock it. Otherwise, we will weld the joint that
// the coordinate belongs to.
if (coordinate.get_locked()) {
if (values.hasColumn(valuePath)) {
coordinate.set_locked(false);
} else {
jointsToWeld.push_back(coordinate.getJoint().getName());
}
} else {
OPENSIM_THROW_IF(!values.hasColumn(valuePath), Exception,
fmt::format("Expected the coordinate values table to "
"contain a column for '{}' (this coordinate is "
"not locked), but it does not.",
coordinate.getAbsolutePathString()))
}
}
// If we detected any joints to be welded, update the model.
if (!jointsToWeld.empty()) {
log_info("Welding the following locked joints (no data provided): ");
for (const auto& jointName : jointsToWeld) {
log_info(" {}", jointName);
}
auto modelProcessor = ModelProcessor(model) |
ModOpReplaceJointsWithWelds(jointsToWeld);
model = modelProcessor.process();
}
// Delete any columns in the coordinate values table that are not in the
// model.
std::vector<std::string> columnsToDelete;
for (const auto& columnLabel : values.getColumnLabels()) {
// Check if the column label ends with "/value".
if (columnLabel.substr(columnLabel.size() - 6) != "/value") {
values.removeColumn(columnLabel);
continue;
}
// Check if the column label contains a coordinate path.
const std::string coordinatePath = columnLabel.substr(
0, columnLabel.size() - std::string("/value").size());
if (!model.hasComponent(coordinatePath)) {
values.removeColumn(columnLabel);
}
}
return values;
}
// Helper function to sample coordinate values around the user-provided
// coordinate trajectory contained in the `values` input table. The
// sampling is defined based on the coordinate bounds and range maps,
// the number of samples per frame, and the Latin hypercube sampling
// algorithm.
TimeSeriesTable sampleCoordinateValues(
const TimeSeriesTable& values,
const CoordinateMap& coordinateBoundsMap,
const CoordinateMap& coordinateRangeMap,
const Settings& settings) {
// Mute the Latin hypercube sampling output, so it doesn't print out for
// every time point.
Logger::Level origLoggerLevel = Logger::getLevel();
Logger::setLevel(Logger::Level::Warn);
// Create a Latin hypercube design to sample the coordinate values.
LatinHypercubeDesign lhs;
lhs.setNumSamples(settings.numSamplesPerFrame);
lhs.setNumVariables((int)values.getNumColumns());
// Helper function for sampling the coordinate values between two time
// indexes.
auto sampleCoordinateValuesSubset = [lhs](
std::vector<int>::iterator begin_iter,
std::vector<int>::iterator end_iter,
const TimeSeriesTable& values,
const CoordinateMap& coordinateBoundsMap,
const CoordinateMap& coordinateRangeMap,
bool useStochasticEvolutionaryLHS) -> SimTK::Matrix {
SimTK::Matrix results(
lhs.getNumSamples()*(int)std::distance(begin_iter, end_iter),
(int)values.getNumColumns());
SimTK::Matrix design(lhs.getNumSamples(), lhs.getNumVariables());
int thisTimeIndex = 0;
for (auto it = begin_iter; it != end_iter; ++it) {
// Generate the design and shift its values between [-1, 1].
if (useStochasticEvolutionaryLHS) {
design = lhs.generateStochasticEvolutionaryDesign();
} else {
design = lhs.generateRandomDesign();
}
design.elementwiseSubtractFromScalarInPlace(0.5);
design *= 2;
int icol = 0;
for (const std::string& label : values.getColumnLabels()) {
const SimTK::VectorView column =
values.getDependentColumn(label);
const auto& bounds = coordinateBoundsMap.at(label);
const auto& range = coordinateRangeMap.at(label);
// Linearly transform the design to the specified bounds for
// each coordinate.
double slope = 0.5*(bounds[1] - bounds[0]);
SimTK::Vector candidateCol = slope*(design.col(icol) + 1.0) +
bounds[0] + column[*it];
// Check that all elements in the column are within the range of
// motion. If not, move the element inside the range of motion
// that is closest to the original value.
for (double& elt : candidateCol) {
if (elt < range[0]) {
elt = range[0];
} else if (elt > range[1]) {
elt = range[1];
}
}
design.updCol(icol) = candidateCol;
++icol;
}
// Store the results.
results.updBlock(thisTimeIndex*lhs.getNumSamples(), 0,
lhs.getNumSamples(), (int)values.getNumColumns()) = design;
++thisTimeIndex;
}
return results;
};
// Determine the number of threads and the stride based on the number of
// forces and the number of threads.
int numTimePoints = static_cast<int>(values.getNumRows());
int numThreads = std::min(numTimePoints, settings.numParallelThreads);
int stride = static_cast<int>(std::floor(numTimePoints / numThreads));
int offset = 0;
// Divide the sampling across multiple threads.
std::vector<int> timeIndexes(values.getNumRows());
std::iota(timeIndexes.begin(), timeIndexes.end(), 0);
std::vector<std::future<SimTK::Matrix>> futures;
for (int thread = 0; thread < numThreads; ++thread) {
auto begin_iter = timeIndexes.begin() + offset;
auto end_iter = (thread == numThreads-1) ?
timeIndexes.end() :
timeIndexes.begin() + offset + stride;
futures.push_back(std::async(std::launch::async,
sampleCoordinateValuesSubset,
begin_iter, end_iter, values, coordinateBoundsMap,
coordinateRangeMap, settings.useStochasticEvolutionaryLHS));
offset += stride;
}
// Wait for threads to finish and collect the results.
std::vector<SimTK::Matrix> outputs;
outputs.reserve(numThreads);
for (int i = 0; i < numThreads; ++i) {
outputs.push_back(futures[i].get());
}
// Reset the logger.
OpenSim::Logger::setLevel(origLoggerLevel);
// Assemble the results into one TimeSeriesTable.
int timeIdx = 0;
const auto& times = values.getIndependentColumn();
TimeSeriesTable valuesSampled;
double dt = (times.size() < 2) ? 0.01 :
(times[1] - times[0]) / (settings.numSamplesPerFrame + 2);
for (int i = 0; i < numThreads; ++i) {
int numTimeIndexes = outputs[i].nrow() / settings.numSamplesPerFrame;
for (int j = 0; j < numTimeIndexes; ++j) {
// Append the original values.
valuesSampled.appendRow(times[timeIdx],
values.getRowAtIndex(timeIdx));
// Update the time step, if possible. Otherwise, use the last time
// step.
if (timeIdx+1 < static_cast<int>(values.getNumRows())) {
dt = (times[timeIdx+1] - times[timeIdx]) /
(settings.numSamplesPerFrame + 2);
}
// Append the sampled values.
for (int irow = 0; irow < settings.numSamplesPerFrame; ++irow) {
valuesSampled.appendRow(times[timeIdx] + (irow + 1)*dt,
outputs[i].row(irow + j*settings.numSamplesPerFrame));
}
++timeIdx;
}
}
valuesSampled.addTableMetaData<std::string>("inDegrees", "no");
valuesSampled.setColumnLabels(values.getColumnLabels());
return valuesSampled;
}
// Helper function to compute path lengths and moment arms for the
// geometry-based paths in the model. The path lengths and moment arms
// are computed using the coordinate values in the `coordinateValues`
// table. The `numThreads` argument specifies the number of threads used
// to parallelize the computations.
void computePathLengthsAndMomentArms(
const Model& model,
const TimeSeriesTable& coordinateValues,
const std::vector<std::string>& forcePaths,
const MomentArmMap& momentArmMap,
const Settings& settings,
TimeSeriesTable& pathLengths,
TimeSeriesTable& momentArms) {
// Precalculate some useful values for the path length and moment arm
// computations.
const int numTimes = static_cast<int>(coordinateValues.getNumRows());
OPENSIM_THROW_IF(numTimes == 0, Exception,
"Tried to compute path lengths and moment arms, but the provided "
"coordinate values table is empty.");
const int numPaths = static_cast<int>(forcePaths.size());
const int numThreads = std::min(numPaths, settings.numParallelThreads);
int numMomentArms = 0;
for (const auto& [forcePath, coordinatePaths] : momentArmMap) {
numMomentArms += coordinatePaths.size();
}
// Define the path calculation worker. The atomic integer 'nextPathIndex'
// controls the path from a thread should perform length and moment arm
// calculations.
std::atomic<int> nextPathIndex(0);
std::vector<SimTK::Matrix> pathResults(numPaths);
auto pathCalculationWorker = [&](Model model, StatesTrajectory statesTraj) {
model.initSystem();
int ipath;
while ((ipath = nextPathIndex.fetch_add(1)) < numPaths) {
const std::string& forcePath = forcePaths[ipath];
log_info("Computing values for path {} of {}: '{}'...",
ipath+1, numPaths, forcePath);
// Resolve the path and coordinate components once, before
// iterating over the states.
const auto& force = model.getComponent<Force>(forcePath);
const AbstractGeometryPath& path =
force.getPropertyByName<AbstractGeometryPath>("path")
.getValue();
std::vector<SimTK::ReferencePtr<const Coordinate>> coordinates;
for (const auto& coordinatePath : momentArmMap.at(forcePath)) {
coordinates.emplace_back(
&model.getComponent<Coordinate>(coordinatePath));
}
const int numCoordsThisPath = static_cast<int>(coordinates.size());
// The result matrix for this path contains the path length
// column followed by the moment arm columns.
SimTK::Matrix& results = pathResults[ipath];
results.resize(numTimes, 1 + numCoordsThisPath);
for (int irow = 0; irow < numTimes; ++irow) {
const auto& state = statesTraj.get(irow);
// Attempt to compute the path length and moment arms for the
// current state. If an error occurs, set the values to NaN.
// This sample will be filtered out later on before fitting
// the polynomial coefficients.
try {
model.realizePosition(state);
// Compute path length.
results(irow, 0) = path.getLength(state);
// Compute moment arms.
for (int ic = 0; ic < numCoordsThisPath; ++ic) {
results(irow, 1 + ic) =
path.computeMomentArm(state, *coordinates[ic]);
}
} catch (const std::exception& e) {
log_warn("Skipping sample at time {:1.2f} s for path "
"'{}' due to error in path computation: {}",
state.getTime(), forcePath, e.what());
// Inject NaN values in the row associated with this
// sample so that it is filtered out later on before
// fitting the polynomial coefficients.
results.updRow(irow).setToNaN();
}
}
}
};
// Construct a StatesTrajectory from the coordinates table.
auto statesTraj = StatesTrajectory::createFromStatesTable(
model, coordinateValues, true, false, false);
OPENSIM_ASSERT_ALWAYS(numTimes == static_cast<int>(statesTraj.getSize()));
// Launch the worker threads.
std::vector<std::future<void>> futures;
futures.reserve(numThreads);
for (int thread = 0; thread < numThreads; ++thread) {
futures.push_back(std::async(std::launch::async,
pathCalculationWorker, model, statesTraj));
}
// Wait for all threads to finish.
for (auto& future : futures) {
future.get();
}
// Assemble the per-path results column-wise into matrices of path
// lengths and moment arms.
SimTK::Matrix lengthsMatrix(numTimes, numPaths);
SimTK::Matrix momentArmsMatrix(numTimes, numMomentArms);
int ipath = 0;
int offset = 0;
for (const auto& path : forcePaths) {
const SimTK::Matrix& results = pathResults[ipath];
const int numCoords = results.ncol() - 1;
lengthsMatrix.updCol(ipath) = results.col(0);
momentArmsMatrix.updBlock(0, offset, numTimes,
numCoords) = results.block(0, 1, numTimes, numCoords);
++ipath;
offset += numCoords;
}
// Assemble the results into TimeSeriesTables.
std::vector<std::string> pathLengthLabels;
pathLengthLabels.reserve(numPaths);
std::vector<std::string> momentArmLabels;
momentArmLabels.reserve(numMomentArms);
for (const auto& forcePath : forcePaths) {
pathLengthLabels.push_back(fmt::format("{}_length", forcePath));
for (const auto& coordinatePath : momentArmMap.at(forcePath)) {
momentArmLabels.push_back(fmt::format("{}_moment_arm_{}",
forcePath,
ComponentPath(coordinatePath).getComponentName()));
}
}
const std::vector<double>& times = coordinateValues.getIndependentColumn();
pathLengths = TimeSeriesTable(times, lengthsMatrix, pathLengthLabels);
momentArms = TimeSeriesTable(times, momentArmsMatrix, momentArmLabels);
}
// Helper function to filter out bad coordinate value samples. Bad samples
// are defined as coordinate values that produce path length and/or moment
// arm values that contain NaNs or deviate by a set number of standard
// deviations away from the nominal trajectories.
void filterSampledData(
const Settings& settings,
TimeSeriesTable& coordinateValues,
TimeSeriesTable& pathLengths,
TimeSeriesTable& momentArms) {
// Remove any path length or moment arm rows that contain NaN values.
std::vector<double> times = coordinateValues.getIndependentColumn();
for (const auto& time : times) {
bool momentArmNaN = SimTK::isNaN(momentArms.getRow(time).sum());
bool pathLengthNaN = SimTK::isNaN(pathLengths.getRow(time).sum());
if (momentArmNaN || pathLengthNaN) {
pathLengths.removeRow(time);
momentArms.removeRow(time);
coordinateValues.removeRow(time);
log_info("NaN path length or moment arm detected at time {:1.2f} s, "
"removing row...", time);
}
}
// Remove sample points that fall outside two standard deviations of the
// data in each column.
double threshold = 5.0;
std::vector<double> rejectedTimePoints;
auto rejectTimePoints = [threshold, &settings](
const TimeSeriesTable& table,
std::vector<double>& rejectedTimePoints) {
const auto& times = table.getIndependentColumn();
int increment = settings.numSamplesPerFrame + 1;
int numOriginalTimes = (int)table.getNumRows() / increment;
for (const auto& label : table.getColumnLabels()) {
SimTK::Vector column = table.getDependentColumn(label);
SimTK::Vector std(numOriginalTimes, 0.0);
for (int i = 0; i < numOriginalTimes; ++i) {
// Compute the mean and standard deviation segments of the
// column segment.
SimTK::Vector segment = column.block(i*increment, 0,
increment, 1).getAsVector();
double mean = segment.sum() / segment.size();
segment.elementwiseSubtractFromScalarInPlace(mean);
std[i] = std::sqrt(segment.normSqr() / segment.size());
}
// Compute the average standard deviation.
double avgStd = std.sum() / std.size();
// Find the time points that deviate too far from the nominal
// values.
int currentNominalIndex = 0;
for (int i = 0; i < column.size(); ++i) {
double nominal = column[currentNominalIndex];
if (std::abs(column[i] - nominal) > threshold * avgStd) {
rejectedTimePoints.push_back(times[i]);
}
if ((i + 1) % increment == 0 &&
currentNominalIndex + increment < column.size()) {
currentNominalIndex += increment;
}
}
}
};
rejectTimePoints(pathLengths, rejectedTimePoints);
rejectTimePoints(momentArms, rejectedTimePoints);
// Remove duplicate time points.
std::sort(rejectedTimePoints.begin(), rejectedTimePoints.end());
rejectedTimePoints.erase(std::unique(rejectedTimePoints.begin(),
rejectedTimePoints.end()), rejectedTimePoints.end());
// Remove the rejected time points.
if (!rejectedTimePoints.empty()) {
double percentTotal = 100.0 * (int)rejectedTimePoints.size() /
(int)coordinateValues.getNumRows();
log_info("Removing {} samples ({:1.1f}% of total) that are larger than "
"{} standard deviations from nominal values...",
rejectedTimePoints.size(), percentTotal, threshold);
for (double time : rejectedTimePoints) {
coordinateValues.removeRow(time);
pathLengths.removeRow(time);
momentArms.removeRow(time);
}
}
}
// Fit to the path length and moment arm samples using all possible
// polynomial coefficients. `coordinates` is the matrix of coordinate values
// for coordinates that the current path depends on. The vector `b` contains
// the path length and moment arm values for the current path.
// We solve for the coefficients of the polynomial using a least squares of
// fit, `Ax = b`. Each row of `A` contains polynomial terms evaluated using
// the coordinate values from a particular point in time. `x` is the vector
// polynomial coefficients. The first N elements of `b` contain the path
// length values, where N is the number of time points. The remaining N*Nc
// rows of `b` contain the moment arm values, where Nc is the number of
// coordinates the path depends on.
int fitAllCoefficients(
const SimTK::Matrix& coordinates,
const SimTK::Vector& b,
const Settings& settings,
SimTK::Vector& coefficients) {
int numTimes = coordinates.nrow();
int numCoordinates = coordinates.ncol();
int order = settings.minimumPolynomialOrder;
while (true) {
// Initialize the multivariate polynomial function.
int numCoefficients = choose(numCoordinates + order, order);
SimTK::Vector dummyCoefficients(numCoefficients, 1.0);
MultivariatePolynomialFunction dummyFunction(dummyCoefficients,
numCoordinates, order);
// Initialize the 'A' matrix.
SimTK::Matrix A(numTimes * (numCoordinates + 1),
numCoefficients, 0.0);
// Fill in the A matrix. This contains the polynomial terms for
// the path length and moment arms.
for (int itime = 0; itime < numTimes; ++itime) {
A(itime, 0, 1, numCoefficients) =
dummyFunction.getTermValues(
coordinates.row(itime).transpose().getAsVector());
for (int ic = 0; ic < numCoordinates; ++ic) {
SimTK::Vector termDerivatives =
dummyFunction.getTermDerivatives({ic},
coordinates.row(itime).transpose().getAsVector())
.negate();
A((ic+1)*numTimes + itime, 0, 1, numCoefficients) =
termDerivatives;
}
}
// Solve the least-squares problem.
SimTK::FactorQTZ factor(A);
factor.solve(b, coefficients);
// Calculate the RMS error.
SimTK::Vector b_fit = A * coefficients;
SimTK::Vector error = b - b_fit;
// If the fit achieves the path length and moment arm thresholds
// we set, then exit the loop.
SimTK::Vector pathLengthError = error.block(
0, 0, numTimes, 1).getAsVector();
double pathLengthRMSError = std::sqrt(
pathLengthError.normSqr() / pathLengthError.size());
bool pathLengthMet = pathLengthRMSError < settings.pathLengthTolerance;
bool momentArmMet = true;
for (int ic = 0; ic < numCoordinates; ++ic) {
SimTK::Vector momentArmError = error.block(
numTimes + ic*numTimes, 0, numTimes, 1).getAsVector();
double momentArmRMSError = std::sqrt(
momentArmError.normSqr() / numTimes);
if (momentArmRMSError > settings.momentArmTolerance) {
momentArmMet = false;
break;
}
}
if ((pathLengthMet && momentArmMet) ||
order == settings.maximumPolynomialOrder) {
break;
}
++order;
}
return order;
}
// Fit to the path length and moment arm samples using stepwise regression
// to find a minimal set of polynomial coefficients. `coordinates` is the
// matrix of coordinate values for coordinates that the current path depends
// on. The vector `b` contains the path length and moment arm values for the
// current path.
void fitCoefficientsStepwiseRegression(
const SimTK::Matrix& coordinates,
const SimTK::Vector& b,
const Settings& settings,
SimTK::Vector& coefficients) {
// Preliminaries.
int numTimes = coordinates.nrow();
int numCoordinates = coordinates.ncol();
int order = settings.maximumPolynomialOrder;
int numCoefficients = choose(numCoordinates + order, order);
// Construct the full 'A' matrix.
SimTK::Vector dummyCoefficients(numCoefficients, 1.0);
MultivariatePolynomialFunction dummyFunction(dummyCoefficients,
numCoordinates, order);
SimTK::Matrix Afull(numTimes * (numCoordinates + 1),
numCoefficients, 0.0);
for (int itime = 0; itime < numTimes; ++itime) {
Afull(itime, 0, 1, numCoefficients) =
dummyFunction.getTermValues(
coordinates.row(itime).transpose().getAsVector());
for (int ic = 0; ic < numCoordinates; ++ic) {
SimTK::Vector termDerivatives =
dummyFunction.getTermDerivatives({ic},
coordinates.row(itime).transpose().getAsVector())
.negate();
Afull((ic+1)*numTimes + itime, 0, 1, numCoefficients) =
termDerivatives;
}
}
// Manage the coefficient indexes that will be included in the final
// polynomial. The "out" indexes are the indexes that are not included in
// the final polynomial, which is initialized to all indexes. The "keep"
// indexes are the indexes that are included in the final polynomial, which
// is initialized to an empty vector.
std::vector<int> outIndexes;
outIndexes.reserve(numCoefficients);
for (int i = 0; i < numCoefficients; ++i) {
outIndexes.push_back(i);
}
std::vector<int> keepIndexes;
SimTK::Vector x_sol;
while (true) {
// Initialize the 'A' matrix.
// The number of terms in the polynomial is the number of "kept"
// coefficients plus one.
int numTerms = static_cast<int>(keepIndexes.size()) + 1;
SimTK::Matrix A(numTimes * (numCoordinates + 1), numTerms, 0.0);
SimTK::Vector x(numTerms, 0.0);
// First, set the columns of 'A' for the "kept" coefficients.
int icol = 0;
for (const auto& ki : keepIndexes) {
A.updCol(icol++) = Afull.col(ki);
}
// Next, loop through all of the remaining "out" coefficients and fit
// the polynomial. We will keep the coefficient that results in the
// smallest RMS error.
SimTK::Real bestError = SimTK::Infinity;
int bestIndex = -1;
for (const auto& oi : outIndexes) {
A.updCol(icol) = Afull.col(oi);
// Solve the least-squares problem.
SimTK::FactorQTZ factor(A);
factor.solve(b, x);
// Calculate the RMS error.
SimTK::Vector b_fit = A * x;
SimTK::Vector error = b - b_fit;
// Calculate the RMS error. Update the best error and index.
double currentError = std::sqrt(error.normSqr() / error.size());
if (currentError < bestError) {
bestError = currentError;
bestIndex = oi;
}
}
// Add the best index to the "keep" indexes and remove it from the "out"
// indexes.
keepIndexes.push_back(bestIndex);
outIndexes.erase(std::remove(outIndexes.begin(), outIndexes.end(),
bestIndex), outIndexes.end());
// Refit the polynomial with the "keep" indexes.
icol = 0;
for (const auto& ki : keepIndexes) {
A.updCol(icol++) = Afull.col(ki);
}
SimTK::FactorQTZ factor(A);
factor.solve(b, x);
SimTK::Vector b_fit = A * x;
SimTK::Vector error = b - b_fit;
// If the current polynomial achieves our path length and moment arm
// tolerances or if the "out" indexes is empty, exit the loop.
SimTK::Vector pathLengthError = error.block(
0, 0, numTimes, 1).getAsVector();
double pathLengthRMSError = std::sqrt(
pathLengthError.normSqr() / pathLengthError.size());
bool pathLengthMet = pathLengthRMSError < settings.pathLengthTolerance;
bool momentArmMet = true;
for (int ic = 0; ic < numCoordinates; ++ic) {
SimTK::Vector momentArmError = error.block(
numTimes + ic*numTimes, 0, numTimes, 1).getAsVector();
double momentArmRMSError = std::sqrt(
momentArmError.normSqr() / numTimes);
if (momentArmRMSError > settings.momentArmTolerance) {
momentArmMet = false;
break;
}
}
int numOutIndexes = static_cast<int>(outIndexes.size());
if ((pathLengthMet && momentArmMet) || !numOutIndexes) {
x_sol = x;
break;
}
}
// Update the coefficients vector
coefficients.resize(numCoefficients);
coefficients.setToZero();
int icoeff = 0;
for (const auto& ki : keepIndexes) {
coefficients.set(ki, x_sol(icoeff++));
}
}
// Helper function to fit polynomial coefficients to the path lengths and
// moment arms computed from the geometry-based paths in the model. The
// `coordinateValues`, `pathLengths`, and `momentArms` table arguments are
// the result of previous model sampling and data filtering steps. The
// `momentArmMap` argument is a map containing the coordinates each path is
// dependent on, which determines the number of independent coordinates
// that each `MultivariatePolynomialFunction` contains to approximate the
// original path.
Set<FunctionBasedPath> fitPolynomialCoefficients(
const TimeSeriesTable& coordinateValues,
const std::vector<std::string>& forcePaths,
const TimeSeriesTable& pathLengths,
const TimeSeriesTable& momentArms,
const MomentArmMap& momentArmMap,
const Settings& settings) {
const int numTimes = (int)coordinateValues.getNumRows();
// Pre-compute variables.
// ----------------------
const int numForces = (int)forcePaths.size();
// Force indexes: one per path-based force (indices into forcePaths).
std::vector<int> forceIndexes;
forceIndexes.reserve(numForces);
for (int i = 0; i < numForces; ++i) {
forceIndexes.push_back(i);
}
// Build a FunctionBasedPath for each path-based force in the model.
// -----------------------------------------------------------------
// Solve A*x = b, where x is the vector of coefficients for the
// FunctionBasedPath, A is a matrix of polynomial terms, and b is a vector
// of path lengths and moment arms.
auto fitForcePolynomialSubset = [&](
std::vector<int>::iterator begin_iter,
std::vector<int>::iterator end_iter,
int thread) -> std::vector<std::unique_ptr<FunctionBasedPath>> {
std::vector<std::unique_ptr<FunctionBasedPath>> thesePaths;
thesePaths.reserve(std::distance(begin_iter, end_iter));
for (auto it = begin_iter; it != end_iter; ++it) {
int iforce = *it;
const std::string& forcePath = forcePaths[iforce];
// Check if the current force is dependent on any coordinates in the
// model. If not, skip it.
if (momentArmMap.find(forcePath) == momentArmMap.end()) {
continue;
}
log_info("Thread {:2d}/{:2d}: fitting coefficients for force "
"'{}'...", thread+1, settings.numParallelThreads,
forcePath);
// The coordinate paths that the current force depends on.
const std::vector<std::string>& coordinatePathsThisForce =
momentArmMap.at(forcePath);
int numCoordinatesThisForce = (int)coordinatePathsThisForce.size();
// Initialize the 'b' vector. This is the same for all polynomial
// orders.
SimTK::Vector b(numTimes * (numCoordinatesThisForce + 1), 0.0);
// The path lengths for this force. This is the first N elements of
// the 'b' vector.
b(0, numTimes) = pathLengths.getDependentColumn(
fmt::format("{}_length", forcePath));
// The moment arms this force and coordinates associated with this
// force. The moment arms are the remaining elements of the 'b'
// vector.
SimTK::Matrix coordinatesThisForce(
numTimes, numCoordinatesThisForce, 0.0);
for (int ic = 0; ic < numCoordinatesThisForce; ++ic) {
const std::string coordinateName = ComponentPath(
coordinatePathsThisForce[ic]).getComponentName();
b((ic+1)*numTimes, numTimes) = momentArms.getDependentColumn(
fmt::format("{}_moment_arm_{}", forcePath,
coordinateName));
const SimTK::VectorView coordinateValuesThisCoordinate =
coordinateValues.getDependentColumn(
fmt::format("{}/value",
coordinatePathsThisForce[ic]));
for (int itime = 0; itime < numTimes; ++itime) {
coordinatesThisForce.set(
itime, ic, coordinateValuesThisCoordinate[itime]);
}
}
// Polynomial fitting.
// -------------------
SimTK::Vector coefficients;
int order;
if (settings.useStepwiseRegression) {
order = settings.maximumPolynomialOrder;
fitCoefficientsStepwiseRegression(coordinatesThisForce, b,
settings, coefficients);
} else {
order = fitAllCoefficients(coordinatesThisForce, b,
settings, coefficients);
}
// Create a FunctionBasedPath for the current path-based force.
MultivariatePolynomialFunction lengthFunction;
lengthFunction.setDimension(numCoordinatesThisForce);
lengthFunction.setOrder(order);
lengthFunction.setCoefficients(coefficients);
auto functionBasedPath = std::make_unique<FunctionBasedPath>();
functionBasedPath->setName(forcePath);
functionBasedPath->setCoordinatePaths(coordinatePathsThisForce);
functionBasedPath->setLengthFunction(lengthFunction);
if (settings.includeMomentArmFunctions) {
for (int iq = 0; iq < numCoordinatesThisForce; ++iq) {
MultivariatePolynomialFunction momentArmFunction =
lengthFunction.generateDerivativeFunction(iq, true);
functionBasedPath->appendMomentArmFunction(
momentArmFunction);
}
}
if (settings.includeLengtheningSpeedFunction) {
MultivariatePolynomialFunction lengtheningSpeedFunction =
lengthFunction.generatePartialVelocityFunction();
functionBasedPath->setLengtheningSpeedFunction(
lengtheningSpeedFunction);
}
// Save the FunctionBasedPath.
thesePaths.push_back(std::move(functionBasedPath));
}
return thesePaths;
};
// Determine the number of threads and the stride based on the number of
// forces and the number of threads.
int numThreads = std::min(numForces, settings.numParallelThreads);
int stride = static_cast<int>(std::floor(numForces / numThreads));
int offset = 0;
// Divide the polynomial fitting across multiple threads.
std::vector<std::future<std::vector<std::unique_ptr<FunctionBasedPath>>>>
futures;
for (int thread = 0; thread < numThreads; ++thread) {
auto begin_iter = forceIndexes.begin() + offset;
auto end_iter = (thread == numThreads-1) ?
forceIndexes.end() :
forceIndexes.begin() + offset + stride;
futures.push_back(std::async(std::launch::async,
fitForcePolynomialSubset,
begin_iter, end_iter, thread));
offset += stride;
}
// Wait for threads to finish and collect the results.
Set<FunctionBasedPath> functionBasedPaths;
for (int thread = 0; thread < numThreads; ++thread) {
auto thesePaths = futures[thread].get();
for (auto& path : thesePaths) {
functionBasedPaths.adoptAndAppend(path.release());
}
}
return functionBasedPaths;
}
// Get the RMS errors between two sets of path lengths and moment arms
// computed from a model with FunctionBasedPaths and the original model. The
// `modelFitted` argument must be the model with the FunctionBasedPaths.
void computeFittingErrors(
const Model& modelFitted,
const TimeSeriesTable& pathLengths,
const TimeSeriesTable& momentArms,
const TimeSeriesTable& pathLengthsFitted,
const TimeSeriesTable& momentArmsFitted,
const Settings& settings) {
// Convert the tolerances to centimeters.
double pathLengthTolerance = settings.pathLengthTolerance * 100.0;
double momentArmTolerance = settings.momentArmTolerance * 100.0;
// Helper function for printing warning messages.
auto printWarningMessage = [](const std::string& pathLengthOrMomentArm,
double tolerance) {
log_warn("-----------------------------------------------------------");
log_warn(fmt::format("The {} RMS error is greater than the prescribed "
"tolerance of {:g} cm.",
pathLengthOrMomentArm, tolerance));
log_warn("");
log_warn("Consider increasing the number of samples per frame or the ");
log_warn("polynomial order and re-fitting the model. If a re-fitting ");
log_warn("is not successful, check that the original model produces ");
log_warn("path lengths and moment arms that are free of ");
log_warn("discontinuities or other irregularities.");
log_warn("-----------------------------------------------------------");
};
// Check inputs.
OPENSIM_ASSERT_ALWAYS(pathLengths.getNumRows() ==
pathLengthsFitted.getNumRows());
OPENSIM_ASSERT_ALWAYS(momentArms.getNumRows() ==
momentArmsFitted.getNumRows());
OPENSIM_ASSERT_ALWAYS(pathLengths.getNumColumns() ==
pathLengthsFitted.getNumColumns());
OPENSIM_ASSERT_ALWAYS(momentArms.getNumColumns() ==
momentArmsFitted.getNumColumns());
const auto& functionBasedPaths =
modelFitted.getComponentList<FunctionBasedPath>();
int numPaths = (int)std::distance(functionBasedPaths.begin(),
functionBasedPaths.end());
OPENSIM_THROW_IF(numPaths == 0, Exception,
"Expected the model to contain 'FunctionBasedPath's, but none were "
"found.");
// Print the path length and moment arm RMS errors for each path.
log_info("");
log_info("Summary of path length and moment arm RMS errors");
log_info("------------------------------------------------");
SimTK::Vector pathLengthRMSErrors((int)pathLengths.getNumColumns());
SimTK::Vector momentArmRMSErrors((int)momentArms.getNumColumns());
int ip = 0;
int ima = 0;
for (const auto& path : modelFitted.getComponentList<FunctionBasedPath>()) {
std::string pathName = path.getAbsolutePathString();
pathName = pathName.substr(0, pathName.length() - 5);
log_info("'{}' path errors:", pathName);
const std::string lengthLabel = fmt::format("{}_length", pathName);