Skip to content

Add independent variable rows to sensitivity toolbox Pynumero-based sensitivity calcs #3655

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion pyomo/contrib/sensitivity_toolbox/pynumero.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def get_dsdp_dfdp(model, theta):
Returns
-------
scipy.sparse.csc_matrix, csc_matrix, ComponentMap, ComponentMap
ds/dp (ns by np), df/dp (1 by np), row map, column map.
ds/dp (ns + np by np), df/dp (1 by np), row map, column map.
The column map maps Pyomo variables p to columns and the
row map maps Pyomo variables s to rows.
"""
Expand Down Expand Up @@ -98,6 +98,15 @@ def get_dsdp_dfdp(model, theta):
_coo_reorder_cols(dfdx, remap=col_remap)
dfdx = dfdx.tocsc()
dfdp = dfdx[0, :ns] @ dsdp + dfdx[0, ns:]

# Add independent variables to the rows as the end
dsdp = scipy.sparse.vstack(
[dsdp, scipy.sparse.identity(len(column_map), format="csc")]
)
n = len(row_map)
for p, i in column_map.items():
row_map[p] = i + n

# return sensitivity of the outputs to p and component maps
return dsdp, dfdp, row_map, column_map

Expand Down
6 changes: 5 additions & 1 deletion pyomo/contrib/sensitivity_toolbox/tests/test_pynumero.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,15 @@ def test_dsdp_dfdp_pyomo_nlp(self):
dsdp, dfdp, rmap, cmap = pnsens.get_dsdp_dfdp(m2, theta)

# Since x1 = p1
assert dsdp.shape == (2, 2)
assert dsdp.shape == (4, 2)
np.testing.assert_almost_equal(dsdp[rmap[m.x1], cmap[m.p1]], 40.0)
np.testing.assert_almost_equal(dsdp[rmap[m.x1], cmap[m.p2]], 0.0)
np.testing.assert_almost_equal(dsdp[rmap[m.x2], cmap[m.p1]], 0.0)
np.testing.assert_almost_equal(dsdp[rmap[m.x2], cmap[m.p2]], 1.0)
np.testing.assert_almost_equal(dsdp[rmap[m.p1], cmap[m.p2]], 0.0)
np.testing.assert_almost_equal(dsdp[rmap[m.p2], cmap[m.p2]], 1.0)
np.testing.assert_almost_equal(dsdp[rmap[m.p1], cmap[m.p1]], 1.0)
np.testing.assert_almost_equal(dsdp[rmap[m.p2], cmap[m.p1]], 0.0)

# if x1 = 2 * p1 and x2 = p2 then
# df/dp1 = 6 p1**2 + p2 = 45.0
Expand Down