Skip to content
Open
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
3 changes: 3 additions & 0 deletions .github/workflows/python-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ on:
pull_request:
paths:
- "SU2_PY/monitor.py"
- "SU2_PY/SU2/eval/**"
- "SU2_PY/tests/**"
- ".github/workflows/python-tests.yml"

Expand All @@ -20,3 +21,5 @@ jobs:
run: pip install numpy pandas matplotlib
- name: Run monitor tests
run: python3 SU2_PY/tests/test_monitor.py
- name: Run design variable scale tests
run: python3 SU2_PY/tests/test_dv_scale.py
20 changes: 16 additions & 4 deletions SU2_PY/SU2/eval/design.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,14 @@ def obj_dp(config, state, this_obj, def_objs):
#: def obj_dp()


def dv_gradient_scale(grad_method, dv_scl):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: a small test of the scaling with SCALE != 1 would protect this from being reverted, since every current testcase uses SCALE = 1. Even a unit test of dv_gradient_scale would help.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a test: SU2_PY/tests/test_dv_scale.py.

It checks that the gradient is scaled the right way for FINDIFF and for the adjoint, using DV scales of 2 and 0.5. The test passes with this PR and fails without it.

I also added it to the Python Tests workflow, so it runs automatically in CI.

"""Factor that turns a gradient from su2grad into the gradient with respect to
the optimizer variable x, where the design variable value is dv_scl * x
(see Config.unpack_dvs). Finite differences perturb x itself, adjoint and
geometry gradients are taken with respect to the design variable value."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional one-liner: in su2grad() (gradients.py), the DIRECTDIFF branch assigns grad = directdiff(...), but the next line uses grads, so DIRECTDIFF always fails with a NameError. Feel free to fix that here. (The scaling itself is right for DIRECTDIFF: the derivative is seeded on the physical DV_VALUE, so it needs dv_scl like the adjoint.)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed, changed grad to grads (commit dc3b000). So DIRECTDIFF works again.

return 1.0 if grad_method == "FINDIFF" else dv_scl

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FINDIFF at a nonzero design (your follow-up issue): please do open it. One extra piece for it: in findiff() (gradients.py), dvs_base comes from DV_VALUE_NEW, which is already physical (scaled), and unpack_dvs(this_dvs, dvs_base) multiplies it by the scale again. So with SCALE != 1 there is a second error on top of the one you saw at scale 1.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing this out. I opened a new PR for it: #3067.

In that PR I removed dvs_base completely. The mesh is already moved to the base design, so now each finite difference run only adds its own small step. This also fixes the double scaling you mentioned.

I tested it on NACA0012 and compared it with a central difference:

  • SCALE = 2: ratio 1.0048 (before the fix: 25.4)
  • SCALE = 0.5: ratio 1.0012

The small leftover difference is normal for a one-sided step.



def obj_df(dvs, config, state=None):
"""vals = SU2.eval.obj_df(dvs,config,state=None)

Expand Down Expand Up @@ -367,8 +375,9 @@ def obj_df(dvs, config, state=None):
global_factor = float(config["OPT_GRADIENT_FACTOR"])
k = 0
for i_dv, dv_scl in enumerate(dv_scales):
dv_factor = dv_gradient_scale(grad_method, dv_scl)
for i_grd in range(dv_size[i_dv]):
grad[k] = grad[k] * global_factor / dv_scl
grad[k] = grad[k] * global_factor * dv_factor
k = k + 1

vals_out.append(grad)
Expand Down Expand Up @@ -397,8 +406,9 @@ def obj_df(dvs, config, state=None):
# scaling and sign
k = 0
for i_dv, dv_scl in enumerate(dv_scales):
dv_factor = dv_gradient_scale(grad_method, dv_scl)
for i_grd in range(dv_size[i_dv]):
grad[k] = grad[k] * sign * scale * global_factor / dv_scl
grad[k] = grad[k] * sign * scale * global_factor * dv_factor
k = k + 1

vals_out.append(grad)
Expand Down Expand Up @@ -492,8 +502,9 @@ def con_dceq(dvs, config, state=None):
# scaling
k = 0
for i_dv, dv_scl in enumerate(dv_scales):
dv_factor = dv_gradient_scale(grad_method, dv_scl)
for i_grd in range(dv_size[i_dv]):
grad[k] = grad[k] * global_factor / dv_scl
grad[k] = grad[k] * global_factor * dv_factor
k = k + 1

vals_out.append(grad)
Expand Down Expand Up @@ -593,8 +604,9 @@ def con_dcieq(dvs, config, state=None):
# scaling and sign
k = 0
for i_dv, dv_scl in enumerate(dv_scales):
dv_factor = dv_gradient_scale(grad_method, dv_scl)
for i_grd in range(dv_size[i_dv]):
grad[k] = grad[k] * sign * global_factor / dv_scl
grad[k] = grad[k] * sign * global_factor * dv_factor
k = k + 1

vals_out.append(grad)
Expand Down
2 changes: 1 addition & 1 deletion SU2_PY/SU2/eval/gradients.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def gradient(func_name, method, config, state=None):
grads = findiff(config, state)

elif method == "DIRECTDIFF":
grad = directdiff(config, state)
grads = directdiff(config, state)

else:
raise Exception("unrecognized gradient method")
Expand Down
54 changes: 54 additions & 0 deletions SU2_PY/tests/test_dv_scale.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#!/usr/bin/env python3

import os
import sys
import unittest
import unittest.mock
from pathlib import Path

# SU2.run needs SU2_RUN at import, no solver is run here
os.environ.setdefault("SU2_RUN", str(Path(__file__).parent))
sys.path.insert(0, str(Path(__file__).parents[1]))

from SU2.eval import design # noqa: E402


class FakeConfig(dict):
def unpack_dvs(self, dvs):
pass


def make_config(method):
return FakeConfig(
GRADIENT_METHOD=method,
OPT_OBJECTIVE={"DRAG": {"SCALE": 1.0, "OBJTYPE": "DEFAULT"}},
OPT_COMBINE_OBJECTIVE="NO",
OPT_GRADIENT_FACTOR="1.0",
MARKER_MONITORING=["airfoil"],
DEFINITION_DV={"SCALE": [2.0, 0.5], "SIZE": [1, 2]},
)


class TestDvGradientScale(unittest.TestCase):
"""The design variable value is SCALE * x, see Config.unpack_dvs."""

def test_factor(self):
self.assertEqual(design.dv_gradient_scale("FINDIFF", 2.0), 1.0)
for method in ("CONTINUOUS_ADJOINT", "DISCRETE_ADJOINT", "DIRECTDIFF"):
self.assertEqual(design.dv_gradient_scale(method, 2.0), 2.0)

def obj_df(self, method):
with unittest.mock.patch.object(
design, "su2grad", return_value=[1.0, 1.0, 1.0]
):
return design.obj_df([0.0, 0.0, 0.0], make_config(method))[0]

def test_obj_df_findiff_is_not_scaled(self):
self.assertEqual(self.obj_df("FINDIFF"), [1.0, 1.0, 1.0])

def test_obj_df_adjoint_is_multiplied_by_scale(self):
self.assertEqual(self.obj_df("DISCRETE_ADJOINT"), [2.0, 0.5, 0.5])


if __name__ == "__main__":
unittest.main()