#!/usr/bin/env python
# coding: utf-8

# # Derivatives in NLSQ
# 
# Copyright (C) 2026 Andreas Kloeckner
# 
# <details>
# <summary>MIT License</summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# </details>

# In[2]:


import sympy as sp


# In[28]:


a1f = sp.Function("a_1")
a2f = sp.Function("a_2")
x, y = sp.symbols("x, y")
g1, g2 = sp.symbols("g_1, g_2")
r1, r2 = sp.symbols("r_1, r_2")


# Make a symbolic quantity for `r` (residual, $\boldsymbol g- \boldsymbol a(\boldsymbol x)$) and `phi`.
# 
# Make sure to use `sp.factor` on `phi`:

# In[29]:


a1 = a1f(x, y)
a2 = a2f(x, y)
a = sp.Matrix([a1, a2])
xvec = sp.Matrix([x, y])
r = a - sp.Matrix([g1, g2])
phi = sp.Rational(1, 2) * sp.factor(r.T@r)
phi


# In[33]:


def subst_r(x):
    return x.subs(r[0], r1).subs(r[1], r2)


# Find the gradient of $\phi$, substitute in `r`:

# In[34]:


subst_r(sp.Matrix([phi.diff(x), phi.diff(y)]))


# Now find the Hessian:

# In[48]:


H = subst_r(sp.Matrix([[phi.diff(i).diff(j) for j in [x, y]] for i in [x,y]]))
H


# For comparison, here is $J_{\boldsymbol r}^TJ_{\boldsymbol r}$:

# In[46]:


J = subst_r(sp.Matrix([list(r.diff(i)) for i in [x, y]]).T)
J.T @ J


# In[50]:


H - J.T @ J


# In[ ]:




