Hybrid_City10000.cpp
Go to the documentation of this file.
1 /* ----------------------------------------------------------------------------
2 
3  * GTSAM Copyright 2010-2020, Georgia Tech Research Corporation,
4  * Atlanta, Georgia 30332-0415
5  * All Rights Reserved
6  * Authors: Frank Dellaert, et al. (see THANKS for the full author list)
7 
8  * See LICENSE for the license information
9 
10  * -------------------------------------------------------------------------- */
11 
20 #include <gtsam/geometry/Pose2.h>
25 #include <gtsam/inference/Symbol.h>
26 #include <gtsam/nonlinear/Values.h>
28 #include <gtsam/slam/PriorFactor.h>
29 #include <gtsam/slam/dataset.h>
30 #include <time.h>
31 
32 #include <cstdlib>
33 #include <fstream>
34 #include <iostream>
35 #include <string>
36 #include <vector>
37 
38 #include "City10000.h"
39 
40 using namespace gtsam;
41 
45 
46 // Experiment Class
47 class Experiment {
50 
51  public:
52  // Parameters with default values
53  size_t maxLoopCount = 8000;
54 
55  // 3000: {1: 62s, 2: 21s, 3: 20s, 4: 31s, 5: 39s} No DT optimizations
56  // 3000: {1: 65s, 2: 20s, 3: 16s, 4: 21s, 5: 28s} With DT optimizations
57  // 3000: {1: 59s, 2: 19s, 3: 18s, 4: 26s, 5: 33s} With DT optimizations +
58  // merge
59  size_t updateFrequency = 3;
60 
61  size_t maxNrHypotheses = 10;
62 
63  size_t reLinearizationFrequency = 10;
64 
65  double marginalThreshold = 0.9999;
66 
67  private:
71 
77  size_t loopCounter, size_t keyS, size_t keyT,
78  const Pose2& measurement) const {
79  DiscreteKey l(L(loopCounter), 2);
80 
81  auto f0 = std::make_shared<BetweenFactor<Pose2>>(
82  X(keyS), X(keyT), measurement, kOpenLoopModel);
83  auto f1 = std::make_shared<BetweenFactor<Pose2>>(
84  X(keyS), X(keyT), measurement, kPoseNoiseModel);
85 
86  std::vector<NonlinearFactorValuePair> factors{{f0, kOpenLoopConstant},
88  HybridNonlinearFactor mixtureFactor(l, factors);
89  return mixtureFactor;
90  }
91 
94  size_t numMeasurements, size_t keyS, size_t keyT, const DiscreteKey& m,
95  const std::vector<Pose2>& poseArray) const {
96  auto f0 = std::make_shared<BetweenFactor<Pose2>>(
97  X(keyS), X(keyT), poseArray[0], kPoseNoiseModel);
98  auto f1 = std::make_shared<BetweenFactor<Pose2>>(
99  X(keyS), X(keyT), poseArray[1], kPoseNoiseModel);
100 
101  std::vector<NonlinearFactorValuePair> factors{{f0, kPoseNoiseConstant},
103  HybridNonlinearFactor mixtureFactor(m, factors);
104  return mixtureFactor;
105  }
106 
108  clock_t smootherUpdate(size_t maxNrHypotheses) {
109  std::cout << "Smoother update: " << newFactors_.size() << std::endl;
110  gttic_(SmootherUpdate);
111  clock_t beforeUpdate = clock();
112  smoother_.update(newFactors_, initial_, maxNrHypotheses);
113  clock_t afterUpdate = clock();
114  allFactors_.push_back(newFactors_);
115  newFactors_.resize(0);
116  return afterUpdate - beforeUpdate;
117  }
118 
120  clock_t reInitialize() {
121  std::cout << "================= Re-Initialize: " << allFactors_.size()
122  << std::endl;
123  clock_t beforeUpdate = clock();
124  allFactors_ = allFactors_.restrict(smoother_.fixedValues());
125  auto linearized = allFactors_.linearize(initial_);
126  auto bayesNet = linearized->eliminateSequential();
127  HybridValues delta = bayesNet->optimize();
128  initial_ = initial_.retract(delta.continuous());
129  smoother_.reInitialize(std::move(*bayesNet));
130  clock_t afterUpdate = clock();
131  std::cout << "Took " << (afterUpdate - beforeUpdate) / CLOCKS_PER_SEC
132  << " seconds." << std::endl;
133  return afterUpdate - beforeUpdate;
134  }
135 
136  public:
138  explicit Experiment(const std::string& filename)
139  : dataset_(filename), smoother_(marginalThreshold) {}
140 
142  void run() {
143  // Initialize local variables
144  size_t discreteCount = 0, index = 0, loopCount = 0, updateCount = 0;
145 
146  std::list<double> timeList;
147 
148  // Set up initial prior
149  Pose2 priorPose(0, 0, 0);
150  initial_.insert(X(0), priorPose);
151  newFactors_.push_back(
152  PriorFactor<Pose2>(X(0), priorPose, kPriorNoiseModel));
153 
154  // Initial update
155  auto time = smootherUpdate(maxNrHypotheses);
156  std::vector<std::pair<size_t, double>> smootherUpdateTimes;
157  smootherUpdateTimes.push_back({index, time});
158 
159  // Flag to decide whether to run smoother update
160  size_t numberOfHybridFactors = 0;
161 
162  // Start main loop
163  Values result;
164  size_t keyS = 0, keyT = 0;
165  clock_t startTime = clock();
166 
167  std::vector<Pose2> poseArray;
168  std::pair<size_t, size_t> keys;
169 
170  while (dataset_.next(&poseArray, &keys) && index < maxLoopCount) {
171  keyS = keys.first;
172  keyT = keys.second;
173  size_t numMeasurements = poseArray.size();
174 
175  // Take the first one as the initial estimate
176  Pose2 odomPose = poseArray[0];
177  if (keyS == keyT - 1) {
178  // Odometry factor
179  if (numMeasurements > 1) {
180  // Add hybrid factor
181  DiscreteKey m(M(discreteCount), numMeasurements);
182  HybridNonlinearFactor mixtureFactor =
183  hybridOdometryFactor(numMeasurements, keyS, keyT, m, poseArray);
184  newFactors_.push_back(mixtureFactor);
185  discreteCount++;
186  numberOfHybridFactors += 1;
187  std::cout << "mixtureFactor: " << keyS << " " << keyT << std::endl;
188  } else {
189  newFactors_.add(BetweenFactor<Pose2>(X(keyS), X(keyT), odomPose,
190  kPoseNoiseModel));
191  }
192  // Insert next pose initial guess
193  initial_.insert(X(keyT), initial_.at<Pose2>(X(keyS)) * odomPose);
194  } else {
195  // Loop closure
196  HybridNonlinearFactor loopFactor =
197  hybridLoopClosureFactor(loopCount, keyS, keyT, odomPose);
198  // print loop closure event keys:
199  std::cout << "Loop closure: " << keyS << " " << keyT << std::endl;
200  newFactors_.add(loopFactor);
201  numberOfHybridFactors += 1;
202  loopCount++;
203  }
204 
205  if (numberOfHybridFactors >= updateFrequency) {
206  auto time = smootherUpdate(maxNrHypotheses);
207  smootherUpdateTimes.push_back({index, time});
208  numberOfHybridFactors = 0;
209  updateCount++;
210 
211  if (updateCount % reLinearizationFrequency == 0) {
212  reInitialize();
213  }
214  }
215 
216  // Record timing for odometry edges only
217  if (keyS == keyT - 1) {
218  clock_t curTime = clock();
219  timeList.push_back(curTime - startTime);
220  }
221 
222  // Print some status every 100 steps
223  if (index % 100 == 0) {
224  std::cout << "Index: " << index << std::endl;
225  if (!timeList.empty()) {
226  std::cout << "Acc_time: " << timeList.back() / CLOCKS_PER_SEC
227  << " seconds" << std::endl;
228  // delta.discrete().print("The Discrete Assignment");
230  tictoc_print_();
231  }
232  }
233 
234  index++;
235  }
236 
237  // Final update
238  time = smootherUpdate(maxNrHypotheses);
239  smootherUpdateTimes.push_back({index, time});
240 
241  // Final optimize
242  gttic_(HybridSmootherOptimize);
243  HybridValues delta = smoother_.optimize();
244  gttoc_(HybridSmootherOptimize);
245 
246  result.insert_or_assign(initial_.retract(delta.continuous()));
247 
248  std::cout << "Final error: " << smoother_.hybridBayesNet().error(delta)
249  << std::endl;
250 
251  clock_t endTime = clock();
252  clock_t totalTime = endTime - startTime;
253  std::cout << "Total time: " << totalTime / CLOCKS_PER_SEC << " seconds"
254  << std::endl;
255 
256  // Write results to file
257  writeResult(result, keyT + 1, "Hybrid_City10000.txt");
258 
259  // Write timing info to file
260  std::ofstream outfileTime;
261  std::string timeFileName = "Hybrid_City10000_time.txt";
262  outfileTime.open(timeFileName);
263  for (auto accTime : timeList) {
264  outfileTime << accTime / CLOCKS_PER_SEC << std::endl;
265  }
266  outfileTime.close();
267  std::cout << "Output " << timeFileName << " file." << std::endl;
268 
269  std::ofstream timingFile;
270  std::string timingFileName = "Hybrid_City10000_timing.txt";
271  timingFile.open(timingFileName);
272  for (size_t i = 0; i < smootherUpdateTimes.size(); i++) {
273  auto p = smootherUpdateTimes.at(i);
274  timingFile << p.first << ", " << p.second / CLOCKS_PER_SEC << std::endl;
275  }
276  timingFile.close();
277  std::cout << "Wrote timing information to " << timingFileName << std::endl;
278  }
279 };
280 
281 /* ************************************************************************* */
282 // Function to parse command-line arguments
283 void parseArguments(int argc, char* argv[], size_t& maxLoopCount,
284  size_t& updateFrequency, size_t& maxNrHypotheses) {
285  for (int i = 1; i < argc; ++i) {
286  std::string arg = argv[i];
287  if (arg == "--max-loop-count" && i + 1 < argc) {
288  maxLoopCount = std::stoul(argv[++i]);
289  } else if (arg == "--update-frequency" && i + 1 < argc) {
290  updateFrequency = std::stoul(argv[++i]);
291  } else if (arg == "--max-nr-hypotheses" && i + 1 < argc) {
292  maxNrHypotheses = std::stoul(argv[++i]);
293  } else if (arg == "--help") {
294  std::cout << "Usage: " << argv[0] << " [options]\n"
295  << "Options:\n"
296  << " --max-loop-count <value> Set the maximum loop "
297  "count (default: 3000)\n"
298  << " --update-frequency <value> Set the update frequency "
299  "(default: 3)\n"
300  << " --max-nr-hypotheses <value> Set the maximum number of "
301  "hypotheses (default: 10)\n"
302  << " --help Show this help message\n";
303  std::exit(0);
304  }
305  }
306 }
307 
308 /* ************************************************************************* */
309 // Main function
310 int main(int argc, char* argv[]) {
311  Experiment experiment(findExampleDataFile("T1_city10000_04.txt"));
312  // Experiment experiment("../data/mh_T1_city10000_04.txt"); //Type #1 only
313  // Experiment experiment("../data/mh_T3b_city10000_10.txt"); //Type #3 only
314  // Experiment experiment("../data/mh_T1_T3_city10000_04.txt"); //Type #1 +
315  // Type #3
316 
317  // Parse command-line arguments
318  parseArguments(argc, argv, experiment.maxLoopCount,
319  experiment.updateFrequency, experiment.maxNrHypotheses);
320 
321  // Run the experiment
322  experiment.run();
323 
324  return 0;
325 }
gtsam::HybridSmoother::hybridBayesNet
const HybridBayesNet & hybridBayesNet() const
Return the Bayes Net posterior.
Definition: HybridSmoother.cpp:273
Pose2.h
2D Pose
gtsam::HybridValues
Definition: HybridValues.h:37
asia::bayesNet
static const DiscreteBayesNet bayesNet
Definition: testDiscreteSearch.cpp:30
Experiment::newFactors_
HybridNonlinearFactorGraph newFactors_
Definition: Hybrid_City10000.cpp:69
test_constructor::f1
auto f1
Definition: testHybridNonlinearFactor.cpp:56
gtsam::HybridSmoother::update
void update(const HybridNonlinearFactorGraph &graph, const Values &initial, std::optional< size_t > maxNrLeaves={}, const std::optional< Ordering > givenOrdering={})
Definition: HybridSmoother.cpp:99
Experiment::smoother_
HybridSmoother smoother_
Definition: Hybrid_City10000.cpp:68
gtsam::FactorGraph::error
double error(const HybridValues &values) const
Definition: FactorGraph-inst.h:66
HybridNonlinearFactorGraph.h
Nonlinear hybrid factor graph that uses type erasure.
main
int main(int argc, char *argv[])
Definition: Hybrid_City10000.cpp:310
keys
const KeyVector keys
Definition: testRegularImplicitSchurFactor.cpp:40
gtsam::symbol_shorthand::M
Key M(std::uint64_t j)
Definition: inference/Symbol.h:160
gtsam::HybridNonlinearFactorGraph
Definition: HybridNonlinearFactorGraph.h:33
simple_graph::factors
const GaussianFactorGraph factors
Definition: testJacobianFactor.cpp:213
Experiment::hybridOdometryFactor
HybridNonlinearFactor hybridOdometryFactor(size_t numMeasurements, size_t keyS, size_t keyT, const DiscreteKey &m, const std::vector< Pose2 > &poseArray) const
Create hybrid odometry factor with discrete measurement choices.
Definition: Hybrid_City10000.cpp:93
gtsam::PriorFactor
Definition: nonlinear/PriorFactor.h:30
City10000Dataset::next
bool next(std::vector< Pose2 > *poseArray, std::pair< size_t, size_t > *keys)
Read and parse the next line.
Definition: City10000.h:81
X
#define X
Definition: icosphere.cpp:20
Experiment::maxLoopCount
size_t maxLoopCount
Definition: Hybrid_City10000.cpp:53
kPriorNoiseModel
auto kPriorNoiseModel
Definition: City10000.h:30
kPoseNoiseConstant
const double kPoseNoiseConstant
Definition: City10000.h:35
result
Values result
Definition: OdometryOptimize.cpp:8
Experiment::initial_
Values initial_
Definition: Hybrid_City10000.cpp:70
HybridSmoother.h
An incremental smoother for hybrid factor graphs.
Experiment::maxNrHypotheses
size_t maxNrHypotheses
Definition: Hybrid_City10000.cpp:61
parseArguments
void parseArguments(int argc, char *argv[], size_t &maxLoopCount, size_t &updateFrequency, size_t &maxNrHypotheses)
Definition: Hybrid_City10000.cpp:283
gtsam::symbol_shorthand::X
Key X(std::uint64_t j)
Definition: inference/Symbol.h:171
Experiment::reInitialize
clock_t reInitialize()
Re-linearize, solve ALL, and re-initialize smoother.
Definition: Hybrid_City10000.cpp:120
gtsam::Values::at
const ValueType at(Key j) const
Definition: Values-inl.h:261
gtsam::Values::retract
Values retract(const VectorValues &delta) const
Definition: Values.cpp:99
gtsam::FactorGraph::resize
virtual void resize(size_t size)
Definition: FactorGraph.h:367
gtsam.examples.PlanarManipulatorExample.delta
def delta(g0, g1)
Definition: PlanarManipulatorExample.py:45
dataset.h
utility functions for loading datasets
test_constructor::f0
auto f0
Definition: testHybridNonlinearFactor.cpp:55
gttoc_
#define gttoc_(label)
Definition: timing.h:273
BetweenFactor.h
gttic_
#define gttic_(label)
Definition: timing.h:268
gtsam::tictoc_finishedIteration_
void tictoc_finishedIteration_()
Definition: timing.h:287
relicense.filename
filename
Definition: relicense.py:57
Experiment
Definition: Hybrid_City10000.cpp:47
l
static const Line3 l(Rot3(), 1, 1)
arg
Definition: cast.h:1419
kPoseNoiseModel
auto kPoseNoiseModel
Definition: City10000.h:33
gtsam::tictoc_print_
void tictoc_print_()
Definition: timing.h:291
gtsam::HybridSmoother::optimize
HybridValues optimize() const
Optimize the hybrid Bayes Net, taking into accound fixed values.
Definition: HybridSmoother.cpp:278
Experiment::updateFrequency
size_t updateFrequency
Definition: Hybrid_City10000.cpp:59
L
MatrixXd L
Definition: LLT_example.cpp:6
Symbol.h
gtsam::symbol_shorthand::L
Key L(std::uint64_t j)
Definition: inference/Symbol.h:159
Experiment::dataset_
City10000Dataset dataset_
The City10000 dataset.
Definition: Hybrid_City10000.cpp:49
m
Matrix3f m
Definition: AngleAxis_mimic_euler.cpp:1
writeResult
void writeResult(const Values &result, size_t numPoses, const std::string &filename="Hybrid_city10000.txt")
Write the result of optimization to file.
Definition: City10000.h:98
time
#define time
Definition: timeAdaptAutoDiff.cpp:31
gtsam::FactorGraph::size
size_t size() const
Definition: FactorGraph.h:297
gtsam::HybridSmoother::reInitialize
void reInitialize(HybridBayesNet &&hybridBayesNet)
Definition: HybridSmoother.cpp:28
gtsam::HybridSmoother
Definition: HybridSmoother.h:28
City10000.h
Class for City10000 dataset.
HybridNonlinearFactor.h
A set of nonlinear factors indexed by a set of discrete keys.
gtsam::HybridNonlinearFactorGraph::restrict
HybridNonlinearFactorGraph restrict(const DiscreteValues &assignment) const
Restrict all factors in the graph to the given discrete values.
Definition: HybridNonlinearFactorGraph.cpp:224
Experiment::Experiment
Experiment(const std::string &filename)
Construct with filename of experiment to run.
Definition: Hybrid_City10000.cpp:138
gtsam
traits
Definition: SFMdata.h:40
Experiment::hybridLoopClosureFactor
HybridNonlinearFactor hybridLoopClosureFactor(size_t loopCounter, size_t keyS, size_t keyT, const Pose2 &measurement) const
Create a hybrid loop closure factor where 0 - loose noise model and 1 - loop noise model.
Definition: Hybrid_City10000.cpp:76
PriorFactor.h
City10000Dataset
Definition: City10000.h:37
gtsam::FactorGraph::push_back
IsDerived< DERIVEDFACTOR > push_back(std::shared_ptr< DERIVEDFACTOR > factor)
Add a factor directly using a shared_ptr.
Definition: FactorGraph.h:147
gtsam::Values
Definition: Values.h:65
gtsam::DiscreteKey
std::pair< Key, size_t > DiscreteKey
Definition: DiscreteKey.h:38
p
float * p
Definition: Tutorial_Map_using.cpp:9
gtsam::Values::insert
void insert(Key j, const Value &val)
Definition: Values.cpp:156
gtsam::HybridNonlinearFactorGraph::linearize
std::shared_ptr< HybridGaussianFactorGraph > linearize(const Values &continuousValues) const
Linearize all the continuous factors in the HybridNonlinearFactorGraph.
Definition: HybridNonlinearFactorGraph.cpp:138
Experiment::smootherUpdate
clock_t smootherUpdate(size_t maxNrHypotheses)
Perform smoother update and optimize the graph.
Definition: Hybrid_City10000.cpp:108
kOpenLoopConstant
const double kOpenLoopConstant
Definition: City10000.h:28
Experiment::run
void run()
Run the main experiment with a given maxLoopCount.
Definition: Hybrid_City10000.cpp:142
gtsam::findExampleDataFile
GTSAM_EXPORT std::string findExampleDataFile(const std::string &name)
Definition: dataset.cpp:70
gtsam::HybridSmoother::fixedValues
const DiscreteValues & fixedValues() const
Return fixed values:
Definition: HybridSmoother.h:50
gtsam::FactorGraph::add
IsDerived< DERIVEDFACTOR > add(std::shared_ptr< DERIVEDFACTOR > factor)
add is a synonym for push_back.
Definition: FactorGraph.h:171
HybridValues.h
kOpenLoopModel
auto kOpenLoopModel
Definition: City10000.h:27
i
int i
Definition: BiCGSTAB_step_by_step.cpp:9
gtsam::HybridNonlinearFactor
Implementation of a discrete-conditioned hybrid factor.
Definition: HybridNonlinearFactor.h:58
measurement
static Point2 measurement(323.0, 240.0)
Values.h
A non-templated config holding any types of Manifold-group elements.
gtsam::Pose2
Definition: Pose2.h:39
gtsam::Values::insert_or_assign
void insert_or_assign(Key j, const Value &val)
If key j exists, update value, else perform an insert.
Definition: Values.cpp:193
gtsam::BetweenFactor
Definition: BetweenFactor.h:40
M
Matrix< RealScalar, Dynamic, Dynamic > M
Definition: bench_gemm.cpp:51


gtsam
Author(s):
autogenerated on Wed Apr 16 2025 03:02:31