Skip to content

Add numeric diff support for Python CostFunction bindings + example updates#84

Open
mrawding wants to merge 2 commits intocvg:mainfrom
mrawding:dev/auto-numeric-diff
Open

Add numeric diff support for Python CostFunction bindings + example updates#84
mrawding wants to merge 2 commits intocvg:mainfrom
mrawding:dev/auto-numeric-diff

Conversation

@mrawding
Copy link

This PR adds numeric-diff support for Python-defined cost functions so users can skip manual Jacobians, aligning behavior more closely with Ceres’ autodiff-focused docs. It also refreshes the Python examples
(hello world, Powell’s, and curve fitting) and adds an autodiff-style Powell’s + Curve Fitting example that mirrors the Ceres documentation flow.

Core NumericDiff Update

pyrceres.CostFunction now has member variable set_use_numerif_diff that allows users to set to True for auto differentiation and skip deriving jacobian movement in cost functions

Example from examples/curve_fitting_autodiff.py

lass ExpResidual(pyceres.CostFunction):
    def __init__(self, x, y_obs):
        super().__init__()
        self.x = x
        self.y_obs = y_obs
        self.set_num_residuals(1)
        self.set_parameter_block_sizes([1, 1])
        self.set_use_numeric_diff(True)



    def Evaluate(self, parameters, residuals, jacobians):
        m = parameters[0][0]
        c = parameters[1][0]

        # Model prediction
        y_pred = math.exp(m * self.x + c)

        # Residual: r = y_pred - y_obs
        residuals[0] = y_pred - self.y_obs
# Comments Show Math Needed To Complete Problem Without NumericDiff
        # if jacobians is not None:
        #     # ∂r/∂m = x * exp(m x + c)
        #     if jacobians[0] is not None:
        #         jacobians[0][0] = self.x * y_pred

        #     # ∂r/∂c = exp(m x + c)
        #     if jacobians[1] is not None:
        #         jacobians[1][0] = y_pred

        return True

examples updates

  • hello.py (solves 1/2(10-x)^2
  • curve_fitting.py (solves e^mx+c)
  • robust_curve_fitting_loss.py (solves curve_fitting equation with random outliers)
  • powells.py
  • powells_autodiff.py
  • curve_fitting_autodiff.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant