### Install SymForce Source: https://symforce.org/index.html Install SymForce using pip. This command installs pre-compiled C++ components for Linux and Mac. ```bash pip install symforce ``` -------------------------------- ### Setup SymForce Environment Source: https://symforce.org/_sources/tutorials/values_tutorial.ipynb.txt Imports necessary SymForce modules and sets the symbolic API and log level. This is a common setup for SymForce notebooks. ```python # Setup import symforce symforce.set_symbolic_api("sympy") symforce.set_log_level("warning") import symforce.symbolic as sf from symforce.notebook_util import display from symforce.notebook_util import set_notebook_defaults from symforce.values import Values set_notebook_defaults() ``` -------------------------------- ### ImuFactor Usage Example Source: https://symforce.org/api-cpp/class/classsym_1_1ImuFactor.html Demonstrates how to create and use ImuFactor for visual-inertial optimization. This example shows setting up variables, integrating IMU measurements between keyframes, creating ImuFactor instances, and optimizing the values. ```cpp enum Var : char { POSE = 'p', // Pose3d VELOCITY = 'v', // Vector3d ACCEL_BIAS = 'A', // Vector3d GYRO_BIAS = 'G', // Vector3d GRAVITY = 'g', // Vector3d EPSILON = 'e' // Scalar }; struct ImuMeasurement { Eigen::Vector3d acceleration; Eigen::Vector3d angular_velocity; double duration; }; int main() { // Dummy function declarations std::vector GetMeasurementsBetween(double start_time, double end_time); std::vector GetKeyFrameTimes(); Eigen::Vector3d GetAccelBiasEstimate(double time); Eigen::Vector3d GetGyroBiasEstimate(double time); void AppendOtherFactors(std::vector & factors); // Example accelerometer and gyroscope covariances const Eigen::Vector3d accel_cov = Eigen::Vector3d::Constant(1e-5); const Eigen::Vector3d gyro_cov = Eigen::Vector3d::Constant(1e-5); std::vector factors; // GetKeyFrameTimes assumed to return at least 2 times std::vector key_frame_times = GetKeyFrameTimes(); // Integrating Imu measurements between keyframes, creating an ImuFactor for each for (int i = 0; i < static_cast(key_frame_times.size()) - 1; i++) { const double start_time = key_frame_times[i]; const double end_time = key_frame_times[i + 1]; const std::vector measurements = GetMeasurementsBetween(start_time, end_time); // ImuPreintegrator should be initialized with the best guesses for the IMU biases sym::ImuPreintegrator integrator(GetAccelBiasEstimate(start_time), GetGyroBiasEstimate(start_time)); for (const ImuMeasurement& meas : measurements) { integrator.IntegrateMeasurement(meas.acceleration, meas.angular_velocity, accel_cov, gyro_cov, meas.duration); } factors.push_back(sym::ImuFactor(integrator) .Factor({{Var::POSE, i}, {Var::VELOCITY, i}, {Var::POSE, i + 1}, {Var::VELOCITY, i + 1}, {Var::ACCEL_BIAS, i}, {Var::GYRO_BIAS, i}, {Var::GRAVITY}, {Var::EPSILON}})); } // Adding any other factors there might be for the problem AppendOtherFactors(factors); sym::Optimizerd optimizer(sym::DefaultOptimizerParams(), factors); // Build Values sym::Valuesd values; for (int i = 0; i < key_frame_times.size(); i++) { values.Set({Var::POSE, i}, sym::Pose3d()); values.Set({Var::VELOCITY, i}, Eigen::Vector3d::Zero()); } for (int i = 0; i < key_frame_times.size() - 1; i++) { values.Set({Var::ACCEL_BIAS, i}, GetAccelBiasEstimate(key_frame_times[i])); values.Set({Var::GYRO_BIAS, i}, GetGyroBiasEstimate(key_frame_times[i])); } // gravity should point towards the direction of acceleration values.Set({Var::GRAVITY}, Eigen::Vector3d(0.0, 0.0, -9.8)); values.Set({Var::EPSILON}, sym::kDefaultEpsilond); // Initialize any other items in values ... optimizer.Optimize(values); } ``` -------------------------------- ### Verify SymForce Installation Source: https://symforce.org/index.html Verify the installation by importing the symbolic API and creating a basic symbolic type in Python. ```python >>> import symforce.symbolic as sf >>> sf.Rot3() ``` -------------------------------- ### Get C++ SymEngine Installation Directory Source: https://symforce.org/_modules/symforce/path_util.html Retrieves the installation directory for the C++ SymEngine components. This path is loaded from the build manifest. ```python from symforce.path_util import cc_sym_install_dir cc_sym_dir = cc_sym_install_dir() print(f"C++ SymEngine directory: {cc_sym_dir}") ``` -------------------------------- ### EigenSparseSolver Usage Example Source: https://symforce.org/api-cpp/class/classsym_1_1EigenSparseSolver.html Demonstrates how to instantiate and use EigenSparseSolver with specific Eigen decomposition types for nonlinear solvers. This setup is typically used when configuring an optimizer. ```cpp using LinearSolver = sym::EigenSparseSolver>>; using NonlinearSolver = sym::LevenbergMarquardtSolver; using Optimizer = sym::Optimizer; Optimizer optimizer{...}; ``` -------------------------------- ### symenginepy_install_dir() Source: https://symforce.org/api/symforce.path_util.html Returns the installation directory for SymEnginePy. ```APIDOC def symenginepy_install_dir() -> _Path_ ``` -------------------------------- ### Verify SymForce Installation Source: https://symforce.org/index.html Verifies a successful SymForce installation by importing the library and checking the symbolic API. It also attempts to import the C++ extension module `cc_sym`. Failure to import `cc_sym` or seeing 'sympy' instead of 'symengine' indicates a broken installation. ```python >>> import symforce >>> symforce.get_symbolic_api() 'symengine' >>> from symforce import cc_sym ``` -------------------------------- ### symenginepy_install_dir Source: https://symforce.org/_modules/symforce/path_util.html Returns the installation directory for SymEnginePy. ```APIDOC ## symenginepy_install_dir ### Description Returns the installation directory for SymEnginePy. ### Returns - Path: The installation directory of SymEnginePy. ``` -------------------------------- ### cc_sym_install_dir Source: https://symforce.org/_modules/symforce/path_util.html Returns the installation directory for C++ SymForce. ```APIDOC ## cc_sym_install_dir ### Description Returns the installation directory for C++ SymForce. ### Returns - Path: The installation directory of C++ SymForce. ``` -------------------------------- ### Install SymForce with Pip Source: https://symforce.org/index.html Installs SymForce and its dependencies using pip. This is the recommended method for users who do not plan to modify the C++ source code frequently. For development with C++ sources, consider building with CMake directly. ```bash pip install . ``` -------------------------------- ### cc_sym_install_dir() Source: https://symforce.org/api/symforce.path_util.html Returns the installation directory for the C++ SymForce component. ```APIDOC def cc_sym_install_dir() -> _Path_ ``` -------------------------------- ### Get All Keys Source: https://symforce.org/api-cpp/namespace/namespacesym.html Retrieves all keys required to evaluate this factor. ```cpp const std::vector &AllKeys() const ``` -------------------------------- ### Get SymEnginePy Installation Directory Source: https://symforce.org/_modules/symforce/path_util.html Retrieves the installation directory for the symenginepy package. This path is determined from the build manifest. ```python from symforce.path_util import symenginepy_install_dir symenginepy_dir = symenginepy_install_dir() print(f"SymEnginePy directory: {symenginepy_dir}") ``` -------------------------------- ### Key Formatting Examples Source: https://symforce.org/api-cpp/file/key_8h.html Demonstrates various ways to construct and format Key objects, showing the resulting string representations. ```cpp Key('C', 13) -> "C_13" Key('f') -> "f" Key('f', 32, 2) -> "f_32_2" Key('A', -2, 123) -> "A_n2_123" Key() -> "NULLKEY" ``` -------------------------------- ### Setup Test Case Environment Source: https://symforce.org/_modules/symforce/test_util/test_case_mixin.html Initializes the test environment by setting the default zero epsilon behavior to FAIL and creating a list to store temporary output directories. ```python def setUp(self) -> None: """ Creates list of temporary directories that will be removed before shutdown (unless debug mode is on) """ super().setUp() # Set to fail on default epsilon == 0 codegen_config.DEFAULT_ZERO_EPSILON_BEHAVIOR = codegen_config.ZeroEpsilonBehavior.FAIL # Storage for temporary output directories self.output_dirs: T.List[Path] = [] ``` -------------------------------- ### Get SymForce Installation Directory Source: https://symforce.org/_modules/symforce/path_util.html Retrieves the installation directory of the symforce Python package. This is useful for locating package resources. ```python from symforce.path_util import symforce_dir sym_dir = symforce_dir() print(f"SymForce directory: {sym_dir}") ``` -------------------------------- ### Setup Imports and Defaults Source: https://symforce.org/_sources/tutorials/geometry_tutorial.ipynb.txt Imports necessary symforce modules and sets the symbolic API to sympy and log level to warning. Also sets notebook display defaults. ```python import symforce symforce.set_symbolic_api("sympy") symforce.set_log_level("warning") import symforce.symbolic as sf from symforce import ops from symforce.notebook_util import display from symforce.notebook_util import set_notebook_defaults set_notebook_defaults() ``` -------------------------------- ### Example Usage of sym::Optimizer Source: https://symforce.org/api-cpp/class/classsym_1_1Optimizer.html Demonstrates the creation of a sym::Optimizer, including setting up values, factors (PriorFactorRot3 and BetweenFactorRot3), optimizer parameters, and finally performing the optimization. Ensure necessary types like sym::Key, sym::Valuesd, sym::Rot3d, sym::Factord, and sym::optimizer_params_t are available. ```cpp // Create a Values sym::Key key0{'R', 0}; sym::Key key1{'R', 1}; sym::Valuesd values; values.Set(key0, sym::Rot3d::Identity()); values.Set(key1, sym::Rot3d::Identity()); // Create some factors std::vector factors; factors.push_back(sym::Factord::Jacobian( [epsilon](const sym::Rot3d& rot, Eigen::Vector3d* const res, Eigen::Matrix3d* const jac) { const sym::Rot3d prior = sym::Rot3d::Random(); const Eigen::Matrix3d sqrt_info = Eigen::Vector3d::Ones().asDiagonal(); sym::PriorFactorRot3(rot, prior, sqrt_info, epsilon, res, jac); }, {key0})); factors.push_back(sym::Factord::Jacobian( [epsilon](const sym::Rot3d& rot, Eigen::Vector3d* const res, Eigen::Matrix3d* const jac) { const sym::Rot3d prior = sym::Rot3d::Random(); const Eigen::Matrix3d sqrt_info = Eigen::Vector3d::Ones().asDiagonal(); sym::PriorFactorRot3(rot, prior, sqrt_info, epsilon, res, jac); }, {key1})); factors.push_back(sym::Factord::Jacobian( [epsilon](const sym::Rot3d& a, const sym::Rot3d& b, Eigen::Vector3d* const res, Eigen::Matrix* const jac) { const Eigen::Matrix3d sqrt_info = Eigen::Vector3d::Ones().asDiagonal(); const sym::Rot3d a_T_b = sym::Rot3d::Random(); sym::BetweenFactorRot3(a, b, a_T_b, sqrt_info, epsilon, res, jac); }, {key0, key1})); // Set up the params sym::optimizer_params_t params = sym::DefaultOptimizerParams(); params.iterations = 50; params.early_exit_min_reduction = 0.0001; // Optimize sym::Optimizer optimizer(params, factors); optimizer.Optimize(values); ``` -------------------------------- ### Matrix Construction Examples Source: https://symforce.org/api/symforce.geo.matrix.html Demonstrates various ways to construct Matrix objects, including zero initialization, initialization with data, and specifying dimensions. Use these methods to create matrices of specific sizes and with initial values. ```python 1) Matrix32() # Zero constructed Matrix32 ``` ```python 2) Matrix(sm.Matrix([[1, 2], [3, 4]])) # Matrix22 with [1, 2, 3, 4] data ``` ```python 3A) Matrix([[1, 2], [3, 4]]) # Matrix22 with [1, 2, 3, 4] data ``` ```python 3B) Matrix22([1, 2, 3, 4]) # Matrix22 with [1, 2, 3, 4] data (must matched fixed shape) ``` ```python 3C) Matrix([1, 2, 3, 4]) # Matrix41 with [1, 2, 3, 4] data - column vector assumed ``` ```python 4) Matrix(4, 3) # Zero constructed Matrix43 ``` ```python 5) Matrix(2, 2, [1, 2, 3, 4]) # Matrix22 with [1, 2, 3, 4] data (first two are shape) ``` ```python 6) Matrix(2, 2, lambda row, col: row + col) # Matrix22 with [0, 1, 1, 2] data ``` ```python 7) Matrix22(1, 2, 3, 4) # Matrix22 with [1, 2, 3, 4] data (must match fixed length) ``` -------------------------------- ### Install Build Dependencies with Pip Source: https://symforce.org/index.html Installs packages required for building and running SymForce using pip. This command installs only the essential build dependencies, not all development tools or test requirements. ```bash pip install -r requirements/build_py3.txt ``` -------------------------------- ### Get Identity Element for Pose3 Source: https://symforce.org/_sources/tutorials/ops_tutorial.ipynb.txt Demonstrates how to get the identity element for a Pose3 type using GroupOps.identity. ```python display(GroupOps.identity(sf.Pose3)) ``` -------------------------------- ### Example Usage of FixedSizeOptimizer Source: https://symforce.org/api-cpp/class/classsym_1_1FixedSizeOptimizer.html Demonstrates how to instantiate and use the FixedSizeOptimizer with custom types. This includes setting up the nonlinear solver and calling the Optimize function. ```cpp using LinearSolverType = sym::SparseCholeskySolver>; using CustomNonlinearSolver = sym::LevenbergMarquardtSolver; using CustomOptimizer = sym::FixedSizeOptimizer; CustomOptimizer optimizer(sym::DefaultOptimizerParams()); CustomValuesType custom_values{...}; optimizer.Optimize(custom_values, LinearizeCustomValues); ``` -------------------------------- ### Setup SymForce Environment Source: https://symforce.org/tutorials/values_tutorial.html Initializes the SymForce symbolic API and logging level. Imports necessary modules for symbolic computation and notebook utilities. ```python import symforce symforce.set_symbolic_api("sympy") symforce.set_log_level("warning") import symforce.symbolic as sf from symforce.notebook_util import display from symforce.notebook_util import set_notebook_defaults from symforce.values import Values set_notebook_defaults() ``` -------------------------------- ### Get Storage Dimension of Pose3 Source: https://symforce.org/_sources/tutorials/ops_tutorial.ipynb.txt Demonstrates how to get the number of scalars required to represent a Pose3 type using StorageOps.storage_dim(). ```python # Number of scalars used to represent a Pose3 (4 quaternion + 3 position) display(StorageOps.storage_dim(sf.Pose3)) ``` -------------------------------- ### _main Source: https://symforce.org/api/symforce.test_util.test_case.html Entry point to run all tests in scope. ```APIDOC ## static _main(* args, ** kwargs) Call this to run all tests in scope. Parameters: * **args** (_Any_) * **kwargs** (_Any_) Return type: None ``` -------------------------------- ### IMU Factor Example Usage Source: https://symforce.org/api-cpp/file/imu__factor_8h.html Demonstrates how to use the ImuFactor within an optimization framework. It involves setting up IMU measurements, preintegration, factor creation, and optimizer initialization. ```cpp enum Var : char { POSE = 'p', // Pose3d VELOCITY = 'v', // Vector3d ACCEL_BIAS = 'A', // Vector3d GYRO_BIAS = 'G', // Vector3d GRAVITY = 'g', // Vector3d EPSILON = 'e' // Scalar }; struct ImuMeasurement { Eigen::Vector3d acceleration; Eigen::Vector3d angular_velocity; double duration; }; int main() { // Dummy function declarations std::vector GetMeasurementsBetween(double start_time, double end_time); std::vector GetKeyFrameTimes(); Eigen::Vector3d GetAccelBiasEstimate(double time); Eigen::Vector3d GetGyroBiasEstimate(double time); void AppendOtherFactors(std::vector & factors); // Example accelerometer and gyroscope covariances const Eigen::Vector3d accel_cov = Eigen::Vector3d::Constant(1e-5); const Eigen::Vector3d gyro_cov = Eigen::Vector3d::Constant(1e-5); std::vector factors; // GetKeyFrameTimes assumed to return at least 2 times std::vector key_frame_times = GetKeyFrameTimes(); // Integrating Imu measurements between keyframes, creating an ImuFactor for each for (int i = 0; i < static_cast(key_frame_times.size()) - 1; i++) { const double start_time = key_frame_times[i]; const double end_time = key_frame_times[i + 1]; const std::vector measurements = GetMeasurementsBetween(start_time, end_time); // ImuPreintegrator should be initialized with the best guesses for the IMU biases sym::ImuPreintegrator integrator(GetAccelBiasEstimate(start_time), GetGyroBiasEstimate(start_time)); for (const ImuMeasurement& meas : measurements) { integrator.IntegrateMeasurement(meas.acceleration, meas.angular_velocity, accel_cov, gyro_cov, meas.duration); } factors.push_back(sym::ImuFactor(integrator) .Factor({{Var::POSE, i}, {Var::VELOCITY, i}, {Var::POSE, i + 1}, {Var::VELOCITY, i + 1}, {Var::ACCEL_BIAS, i}, {Var::GYRO_BIAS, i}, {Var::GRAVITY}, {Var::EPSILON}})); } // Adding any other factors there might be for the problem AppendOtherFactors(factors); sym::Optimizerd optimizer(sym::DefaultOptimizerParams(), factors); // Build Values sym::Valuesd values; for (int i = 0; i < key_frame_times.size(); i++) { values.Set({Var::POSE, i}, sym::Pose3d()); values.Set({Var::VELOCITY, i}, Eigen::Vector3d::Zero()); } for (int i = 0; i < key_frame_times.size() - 1; i++) { values.Set({Var::ACCEL_BIAS, i}, GetAccelBiasEstimate(key_frame_times[i])); values.Set({Var::GYRO_BIAS, i}, GetGyroBiasEstimate(key_frame_times[i])); } // gravity should point towards the direction of acceleration values.Set({Var::GRAVITY}, Eigen::Vector3d(0.0, 0.0, -9.8)); values.Set({Var::EPSILON}, sym::kDefaultEpsilond); // Initialize any other items in values ... optimizer.Optimize(values); } ``` -------------------------------- ### Optimizer Usage Example Source: https://symforce.org/_modules/symforce/opt/optimizer.html Demonstrates how to use an Optimizer instance by providing an initial guess and calling the optimize method. ```python initial_guess = Values(...) result = optimizer.optimize(initial_guess) print(result.optimized_values) ``` -------------------------------- ### Values Output Format Example Source: https://symforce.org/api-cpp/namespace/namespacesym.html Example output format for printing a Values object, showing its structure and contents. ```plaintext Valuesd entries=4 array=8 storage_dim=7 tangent_dim=6 R_1 [0:4] --> f_1 [5:6] --> 4.2 f_2 [6:7] --> 4.3 d_1 [7:8] --> 4.3 > ``` -------------------------------- ### Get Storage Dimension of List of Pose3 Source: https://symforce.org/_sources/tutorials/ops_tutorial.ipynb.txt Illustrates element-wise operations on containers by getting the total storage dimension for a list of Pose3 objects. ```python # Element-wise operations on lists of objects display(StorageOps.storage_dim([sf.Pose3, sf.Pose3])) ``` -------------------------------- ### Setup SymForce Environment Source: https://symforce.org/_sources/tutorials/ops_tutorial.ipynb.txt Sets the symbolic API to sympy and the log level to warning. Imports necessary SymForce modules and utility functions for notebook display and default settings. ```python import symforce symforce.set_symbolic_api("sympy") symforce.set_log_level("warning") import symforce.symbolic as sf from symforce.notebook_util import display from symforce.notebook_util import set_notebook_defaults from symforce.ops import GroupOps from symforce.ops import LieGroupOps from symforce.ops import StorageOps from symforce.values import Values set_notebook_defaults() ``` -------------------------------- ### Matrix Construction Examples Source: https://symforce.org/_sources/tutorials/geometry_tutorial.ipynb.txt Provides multiple ways to construct a 2x3 matrix (sf.Matrix23) using SymForce, including from lists, specified dimensions, and aliases. Demonstrates flexibility in matrix initialization. ```python # Matrix construction. The statements below all create the same 2x3 matrix object # Construction from 2D list m1 = sf.Matrix([[1, 2, 3], [4, 5, 6]]) # Construction using specified size + data m2 = sf.Matrix(2, 3, [1, 2, 3, 4, 5, 6]) # sf.MatrixNM creates a matrix with shape NxM (defined by default for 6x6 # matrices and smaller) m3 = sf.Matrix23(1, 2, 3, 4, 5, 6) m4 = sf.Matrix23([1, 2, 3, 4, 5, 6]) # Construction using aliases m5 = sf.M([[1, 2, 3], [4, 5, 6]]) m6 = sf.M(2, 3, [1, 2, 3, 4, 5, 6]) m7 = sf.M23(1, 2, 3, 4, 5, 6) m8 = sf.M23([1, 2, 3, 4, 5, 6]) # Construction from block matrices of appropriate dimensions m9 = sf.Matrix23.block_matrix([[sf.M13([1, 2, 3])], [sf.M13([3, 4, 5])]]) ``` -------------------------------- ### StorageOps for SphericalCameraCal Source: https://symforce.org/api-gen-cpp/namespace/namespacesym.html Provides C++ StorageOps implementation for symforce.cam.spherical_camera_cal.SphericalCameraCal. It includes methods to get storage dimension, convert to and from storage, and get the type enum. ```APIDOC ## StorageOps> ### Description C++ StorageOps implementation for symforce.cam.spherical_camera_cal.SphericalCameraCal. ### Public Types - `using T = SphericalCameraCal` - `using Scalar = ScalarType` ### Public Static Functions - `static inline constexpr int32_t StorageDim()`: Returns the dimension of the storage. - `static void ToStorage(const T &a, ScalarType *out)`: Converts a SphericalCameraCal object to its storage representation. - `static T FromStorage(const ScalarType *data)`: Converts storage data to a SphericalCameraCal object. - `static inline constexpr type_t TypeEnum()`: Returns the type enum for SphericalCameraCal. ``` -------------------------------- ### StorageOps for PolynomialCameraCal Source: https://symforce.org/api-gen-cpp/namespace/namespacesym.html Provides C++ StorageOps implementation for symforce.cam.polynomial_camera_cal.PolynomialCameraCal. It includes methods to get storage dimension, convert to and from storage, and get the type enum. ```APIDOC ## StorageOps> ### Description C++ StorageOps implementation for symforce.cam.polynomial_camera_cal.PolynomialCameraCal. ### Public Types - `using T = PolynomialCameraCal` - `using Scalar = ScalarType` ### Public Static Functions - `static inline constexpr int32_t StorageDim()`: Returns the dimension of the storage. - `static void ToStorage(const T &a, ScalarType *out)`: Converts a PolynomialCameraCal object to its storage representation. - `static T FromStorage(const ScalarType *data)`: Converts storage data to a PolynomialCameraCal object. - `static inline constexpr type_t TypeEnum()`: Returns the type enum for PolynomialCameraCal. ``` -------------------------------- ### Optimize a nonlinear least-squares problem Source: https://symforce.org/api-cpp/namespace/namespacesym.html Example of setting up and running an optimizer for a nonlinear least-squares problem. This involves creating values, defining factors (e.g., PriorFactorRot3, BetweenFactorRot3), configuring optimizer parameters, and then calling the Optimize method. Ensure all necessary headers are included. ```cpp #include // Create a Values sym::Key key0{'R', 0}; sym::Key key1{'R', 1}; sym::Valuesd values; values.Set(key0, sym::Rot3d::Identity()); values.Set(key1, sym::Rot3d::Identity()); // Create some factors std::vector factors; factors.push_back(sym::Factord::Jacobian( [epsilon](const sym::Rot3d& rot, Eigen::Vector3d* const res, Eigen::Matrix3d* const jac) { const sym::Rot3d prior = sym::Rot3d::Random(); const Eigen::Matrix3d sqrt_info = Eigen::Vector3d::Ones().asDiagonal(); sym::PriorFactorRot3(rot, prior, sqrt_info, epsilon, res, jac); }, {key0})); factors.push_back(sym::Factord::Jacobian( [epsilon](const sym::Rot3d& rot, Eigen::Vector3d* const res, Eigen::Matrix3d* const jac) { const sym::Rot3d prior = sym::Rot3d::Random(); const Eigen::Matrix3d sqrt_info = Eigen::Vector3d::Ones().asDiagonal(); sym::PriorFactorRot3(rot, prior, sqrt_info, epsilon, res, jac); }, {key1})); factors.push_back(sym::Factord::Jacobian( [epsilon](const sym::Rot3d& a, const sym::Rot3d& b, Eigen::Vector3d* const res, Eigen::Matrix* const jac) { const Eigen::Matrix3d sqrt_info = Eigen::Vector3d::Ones().asDiagonal(); const sym::Rot3d a_T_b = sym::Rot3d::Random(); sym::BetweenFactorRot3(a, b, a_T_b, sqrt_info, epsilon, res, jac); }, {key0, key1})); // Set up the params sym::optimizer_params_t params = sym::DefaultOptimizerParams(); params.iterations = 50; params.early_exit_min_reduction = 0.0001; // Optimize sym::Optimizer optimizer(params, factors); optimizer.Optimize(values); ``` -------------------------------- ### Example of Picking Generated Keys Source: https://symforce.org/_modules/symforce/values/generated_key_selection.html Demonstrates how variable names are mapped to generated keys, showing the logic for handling simple names, names with numbers, and names with underscores. ```python pick_generated_keys_for_variable_names(['foo', 'foo2', 'foo_bar', 'foo_bar2', 'foo_baz']) ``` -------------------------------- ### StorageOps for OrthographicCameraCal Source: https://symforce.org/api-gen-cpp/namespace/namespacesym.html Provides C++ StorageOps implementation for symforce.cam.orthographic_camera_cal.OrthographicCameraCal. It includes methods to get storage dimension, convert to and from storage, and get the type enum. ```APIDOC ## StorageOps> ### Description C++ StorageOps implementation for symforce.cam.orthographic_camera_cal.OrthographicCameraCal. ### Public Types - `using T = OrthographicCameraCal` - `using Scalar = ScalarType` ### Public Static Functions - `static inline constexpr int32_t StorageDim()`: Returns the dimension of the storage. - `static void ToStorage(const T &a, ScalarType *out)`: Converts an OrthographicCameraCal object to its storage representation. - `static T FromStorage(const ScalarType *data)`: Converts storage data to an OrthographicCameraCal object. - `static inline constexpr type_t TypeEnum()`: Returns the type enum for OrthographicCameraCal. ``` -------------------------------- ### StorageOps for LinearCameraCal Source: https://symforce.org/api-gen-cpp/namespace/namespacesym.html Provides C++ StorageOps implementation for symforce.cam.linear_camera_cal.LinearCameraCal. It includes methods to get storage dimension, convert to and from storage, and get the type enum. ```APIDOC ## StorageOps> ### Description C++ StorageOps implementation for symforce.cam.linear_camera_cal.LinearCameraCal. ### Public Types - `using T = LinearCameraCal` - `using Scalar = ScalarType` ### Public Static Functions - `static inline constexpr int32_t StorageDim()`: Returns the dimension of the storage. - `static void ToStorage(const T &a, ScalarType *out)`: Converts a LinearCameraCal object to its storage representation. - `static T FromStorage(const ScalarType *data)`: Converts storage data to a LinearCameraCal object. - `static inline constexpr type_t TypeEnum()`: Returns the type enum for LinearCameraCal. ``` -------------------------------- ### Setup Symforce Environment Source: https://symforce.org/_sources/tutorials/codegen_tutorial.ipynb.txt Imports necessary symforce modules and sets up the symbolic API, log level, and epsilon to a symbol for safe code generation. This is a prerequisite for most symforce operations. ```python import numpy as np import symforce symforce.set_symbolic_api("symengine") symforce.set_log_level("warning") symforce.set_epsilon_to_symbol() import symforce.symbolic as sf from symforce import codegen from symforce.codegen import codegen_util from symforce.notebook_util import display from symforce.notebook_util import display_code_file from symforce.notebook_util import set_notebook_defaults from symforce.values import Values set_notebook_defaults() ``` -------------------------------- ### StorageOps for Rot3 Source: https://symforce.org/api-gen-cpp/namespace/namespacesym.html Provides C++ StorageOps implementation for symforce.geo.rot3.Rot3. It includes methods to get storage dimension, convert to and from storage, get the type enum, and generate random rotations. ```APIDOC ## StorageOps> ### Description C++ StorageOps implementation for symforce.geo.rot3.Rot3. ### Public Types - `using T = Rot3` - `using Scalar = ScalarType` ### Public Static Functions - `static inline constexpr int32_t StorageDim()`: Returns the dimension of the storage. - `static void ToStorage(const T &a, ScalarType *out)`: Converts a Rot3 object to its storage representation. - `static T FromStorage(const ScalarType *data)`: Converts storage data to a Rot3 object. - `static inline constexpr type_t TypeEnum()`: Returns the type enum for Rot3. - `template static inline T Random(Generator &gen)`: Generates a random Rot3 object using the provided generator. ``` -------------------------------- ### Optimizer Creation with Single Factor Source: https://symforce.org/_modules/symforce/opt/optimizer.html Example of creating an Optimizer instance with a single Factor and specifying the keys to be optimized. ```python factor = Factor( [my_key_0, my_key_1, my_key_2], my_residual_function ) optimizer = Optimizer( factors=[factor], optimized_keys=[my_key_0, my_key_1], ) ``` -------------------------------- ### Notebook Utilities Setup Source: https://symforce.org/_sources/tutorials/sympy_tutorial.ipynb.txt Import and set up utility functions for use in Jupyter notebooks, including display, expression tree printing, and default notebook settings. ```python from symforce.notebook_util import display from symforce.notebook_util import print_expression_tree from symforce.notebook_util import set_notebook_defaults set_notebook_defaults() ``` -------------------------------- ### StorageOps for Rot2 Source: https://symforce.org/api-gen-cpp/namespace/namespacesym.html Provides C++ StorageOps implementation for symforce.geo.rot2.Rot2. It includes methods to get storage dimension, convert to and from storage, get the type enum, and generate random rotations. ```APIDOC ## StorageOps> ### Description C++ StorageOps implementation for symforce.geo.rot2.Rot2. ### Public Types - `using T = Rot2` - `using Scalar = ScalarType` ### Public Static Functions - `static inline constexpr int32_t StorageDim()`: Returns the dimension of the storage. - `static void ToStorage(const T &a, ScalarType *out)`: Converts a Rot2 object to its storage representation. - `static T FromStorage(const ScalarType *data)`: Converts storage data to a Rot2 object. - `static inline constexpr type_t TypeEnum()`: Returns the type enum for Rot2. - `template static inline T Random(Generator &gen)`: Generates a random Rot2 object using the provided generator. ``` -------------------------------- ### StorageOps for Pose3 Source: https://symforce.org/api-gen-cpp/namespace/namespacesym.html Provides C++ StorageOps implementation for symforce.geo.pose3.Pose3. It includes methods to get storage dimension, convert to and from storage, get the type enum, and generate random poses. ```APIDOC ## StorageOps> ### Description C++ StorageOps implementation for symforce.geo.pose3.Pose3. ### Public Types - `using T = Pose3` - `using Scalar = ScalarType` ### Public Static Functions - `static inline constexpr int32_t StorageDim()`: Returns the dimension of the storage. - `static void ToStorage(const T &a, ScalarType *out)`: Converts a Pose3 object to its storage representation. - `static T FromStorage(const ScalarType *data)`: Converts storage data to a Pose3 object. - `static inline constexpr type_t TypeEnum()`: Returns the type enum for Pose3. - `template static inline T Random(Generator &gen)`: Generates a random Pose3 object using the provided generator. ``` -------------------------------- ### StorageOps for Pose2 Source: https://symforce.org/api-gen-cpp/namespace/namespacesym.html Provides C++ StorageOps implementation for symforce.geo.pose2.Pose2. It includes methods to get storage dimension, convert to and from storage, get the type enum, and generate random poses. ```APIDOC ## StorageOps> ### Description C++ StorageOps implementation for symforce.geo.pose2.Pose2. ### Public Types - `using T = Pose2` - `using Scalar = ScalarType` ### Public Static Functions - `static inline constexpr int32_t StorageDim()`: Returns the dimension of the storage. - `static void ToStorage(const T &a, ScalarType *out)`: Converts a Pose2 object to its storage representation. - `static T FromStorage(const ScalarType *data)`: Converts storage data to a Pose2 object. - `static inline constexpr type_t TypeEnum()`: Returns the type enum for Pose2. - `template static inline T Random(Generator &gen)`: Generates a random Pose2 object using the provided generator. ``` -------------------------------- ### main Source: https://symforce.org/api/symforce.benchmarks.run_benchmarks.html The main entry point for running benchmarks, optionally specifying a particular benchmark to execute. ```APIDOC ## main ### Description Orchestrates the execution of benchmarks. It can run all configured benchmarks or a single specified benchmark, saving the output to a designated directory. ### Parameters * **benchmark** (str | None) - The name of a specific benchmark to run. If None, all benchmarks are executed. * **out_dir** (str) - The directory where the benchmark outputs will be saved. Defaults to 'benchmark_outputs'. ``` -------------------------------- ### Get Prettier Command Source: https://symforce.org/_modules/symforce/codegen/format_util.html Helper function to get the command to run prettier with necessary arguments. It checks for a local prettier binary specified in paths.json or falls back to npx/yarn. ```python _prettier_cmd: T.Optional[T.List[str]] = None def _get_prettier_cmd() -> T.List[str]: """ Returns a command to run prettier with any necessary args """ global _prettier_cmd # noqa: PLW0603 if _prettier_cmd is not None: return _prettier_cmd # A path to a local prettier binary can be specified in the paths.json file with they key # "prettier_bin_path". The path should be relative to the symforce root directory. # If not provided, we will use npx or yarn if installed. paths_file = symforce_dir() / "build" / "paths.json" ``` -------------------------------- ### Editable Install SymForce with Pip Source: https://symforce.org/index.html Performs an editable installation of SymForce using pip. This method is useful when modifying the Python components of SymForce, as changes will be reflected without needing to reinstall. ```bash pip install -e . ``` -------------------------------- ### Install GMP Package Source: https://symforce.org/index.html Installs the GMP (GNU Multiple Precision Arithmetic Library) package, which is a dependency for building SymForce. Choose the command appropriate for your operating system or package manager. ```bash apt install libgmp-dev # Ubuntu ``` ```bash brew install gmp # Mac ``` ```bash conda install -c conda-forge gmp # Conda ``` -------------------------------- ### Optimizer Creation with OptimizationProblem (Symbolic Factors) Source: https://symforce.org/_modules/symforce/opt/optimizer.html Illustrates creating an Optimizer from an OptimizationProblem using make_symbolic_factors. Symbolic factors are converted to numeric factors upon optimizer creation, and linearization functions are generated at that time. ```python problem = OptimizationProblem(subproblems=[...], residual_blocks=...) factors = problem.make_symbolic_factors("my_problem") optimizer = Optimizer(factors, problem.optimized_keys()) ``` -------------------------------- ### Get Memory Type of Storage or Pair Source: https://symforce.org/_modules/symforce/caspar/memory/pair.html Determines and returns the underlying storage type for a given Storage object, Pair, or their types. Raises an error if trying to get the type from an unannotated Pair. ```python [docs] def get_memtype( storage_or_pair: T.Union[T.Type[Storage], T.Type[Pair], Storage, Pair], ) -> T.Type[Storage]: if is_pair(storage_or_pair): if storage_or_pair is Pair: raise ValueError("Cannot get type from unannotated Pair") elif T.get_origin(storage_or_pair) is Pair: return T.get_args(storage_or_pair)[0] elif isinstance(storage_or_pair, Pair): return storage_or_pair.data[0].__class__ if isinstance(storage_or_pair, type): storage_or_pair = T.cast(T.Type[Storage], storage_or_pair) return storage_or_pair storage_or_pair = T.cast(Storage, storage_or_pair) return storage_or_pair.__class__ ``` -------------------------------- ### Matrix Construction Examples Source: https://symforce.org/_modules/symforce/geo/matrix.html Demonstrates various ways to construct Matrix objects, including fixed-size types, from SymPy matrices, lists, and lambda functions. Note that fixed-size constructors require matching dimensions. ```python Matrix32() # Zero constructed Matrix32 ``` ```python Matrix(sm.Matrix([[1, 2], [3, 4]])) # Matrix22 with [1, 2, 3, 4] data ``` ```python Matrix([[1, 2], [3, 4]]) # Matrix22 with [1, 2, 3, 4] data ``` ```python Matrix22([1, 2, 3, 4]) # Matrix22 with [1, 2, 3, 4] data (must matched fixed shape) ``` ```python Matrix([1, 2, 3, 4]) # Matrix41 with [1, 2, 3, 4] data - column vector assumed ``` ```python Matrix(4, 3) # Zero constructed Matrix43 ``` ```python Matrix(2, 2, [1, 2, 3, 4]) # Matrix22 with [1, 2, 3, 4] data (first two are shape) ``` ```python Matrix(2, 2, lambda row, col: row + col) # Matrix22 with [0, 1, 1, 2] data ``` ```python Matrix22(1, 2, 3, 4) # Matrix22 with [1, 2, 3, 4] data (must match fixed length) ``` -------------------------------- ### Example Usage of LevenbergMarquardtSolver Source: https://symforce.org/api-cpp/class/classsym_1_1LevenbergMarquardtSolver.html Demonstrates how to set up and use the LevenbergMarquardtSolver for a nonlinear least squares problem. This includes defining a linearization function, initializing values, creating the solver, and iterating until convergence. ```cpp constexpr const int M = 9; constexpr const int N = 5; // Create a function that computes the residual (a linear residual for this example) const auto J_MN = sym::RandomNormalMatrix(gen); const auto linearize_func = [&J_MN](const sym::Valuesd& values, sym::SparseLinearizationd* const linearization) { const auto state_vec = values.At('v'); linearization->residual = J_MN * state_vec; linearization->hessian_lower = (J_MN.transpose() * J_MN).sparseView(); linearization->jacobian = J_MN.sparseView(); linearization->rhs = J_MN.transpose() * linearization->residual; }; // Create a Values sym::Valuesd values_init{}; values_init.Set('v', (StateVector::Ones() * 100).eval()); // Create a Solver sym::LevenbergMarquardtSolverd solver(params, "", kEpsilon); solver.SetIndex(values_init.CreateIndex({'v'})); solver.Reset(values_init); // Iterate to convergence sym::optimization_stats_t stats; bool should_early_exit = false; while (!should_early_exit) { should_early_exit = solver.Iterate(linearize_func, &stats); } // Get the best values sym::Valuesd values_final = solver.GetBestValues(); ``` -------------------------------- ### Retrieve SymForce Version Source: https://symforce.org/_modules/symforce.html Attempts to retrieve the installed version of the symforce package using importlib.metadata. If the package is not installed, it falls back to using setuptools_scm. If neither method succeeds, the __version__ attribute will not be set. ```python # ------------------------------------------------------------------------------------------------- # Version # ------------------------------------------------------------------------------------------------- # isort: split from importlib.metadata import PackageNotFoundError from importlib.metadata import version try: __version__ = version("symforce") except PackageNotFoundError: logger.debug( "symforce package is not being run from an installed context; falling back to" " setuptools_scm for __version__" ) try: import setuptools_scm except ImportError: # setuptools_scm isn't required to be installed logger.debug("setuptools_scm not installed; __version__ will not be set") else: try: __version__ = setuptools_scm.get_version(root="..", relative_to=__file__) except LookupError: logger.debug("setuptools_scm failed to find version; __version__ will not be set") ``` -------------------------------- ### Optimizer Creation with Numeric Factors from OptimizationProblem Source: https://symforce.org/api/symforce.opt.optimizer.html Shows how to create an Optimizer using numeric factors generated from an OptimizationProblem, with linearization performed with respect to the problem's optimized keys. ```python problem = OptimizationProblem(subproblems=[...], residual_blocks=...) factors = problem.make_numeric_factors("my_problem") optimizer = Optimizer(factors) ``` -------------------------------- ### NonlinearSolver Source: https://symforce.org/api-cpp/class/classsym_1_1FixedSizeOptimizer.html Get the NonlinearSolver object. ```APIDOC ## NonlinearSolver ### Description Get the NonlinearSolver object. ### Signature const NonlinearSolverType &NonlinearSolver() const ## NonlinearSolver ### Description Get the NonlinearSolver object. ### Signature NonlinearSolverType &NonlinearSolver() ``` -------------------------------- ### Example Usage of pick_generated_keys_for_variable_names Source: https://symforce.org/api/symforce.values.generated_key_selection.html Demonstrates how to use the pick_generated_keys_for_variable_names function to map a list of variable names to generated keys. Shows the expected output format for various naming conventions. ```python pick_generated_keys_for_variable_names(['foo', 'foo2', 'foo_bar', 'foo_bar2', 'foo_baz']) ``` ```python { 'foo': ('f', None), 'foo2': ('f', 2), 'foo_bar': ('F', None), 'foo_bar2': ('F', 2), 'foo_baz': ('b', None) } ``` -------------------------------- ### get_scope Source: https://symforce.org/api/symforce.internal.symbolic.html Gets the current scope. ```APIDOC ## get_scope ### Description Gets the current scope. ### Return Type str ``` -------------------------------- ### Initialize Optimizer with Factors Source: https://symforce.org/index.html Initialize an Optimizer with the defined factors and specify which keys to optimize. Debug statistics can be enabled for detailed iteration analysis. ```python from symforce.opt.optimizer import Optimizer optimizer = Optimizer( factors=factors, optimized_keys=[f"poses[{i}]" for i in range(num_poses)], # So that we save more information about each iteration, to visualize later: debug_stats=True, ) ``` -------------------------------- ### EigenSparseSolver Usage Example Source: https://symforce.org/api-cpp/file/eigen__sparse__solver_8h.html Demonstrates how to use EigenSparseSolver with LevenbergMarquardtSolver and Optimizer. Requires including the eigen_sparse_solver.h header. ```cpp using LinearSolver = sym::EigenSparseSolver>>; using NonlinearSolver = sym::LevenbergMarquardtSolver; using Optimizer = sym::Optimizer; Optimizer optimizer{...}; ```