def test_penalty_custom_fail(penalty_origin, value): def custom_no_mult(ocp, nlp, t, x, u, p): my_values = DM.zeros((12, 1)) + x[0] return my_values def custom_with_mult(ocp, nlp, t, x, u, p, mult): my_values = DM.zeros((12, 1)) + x[0] * mult return my_values ocp = prepare_test_ocp() x = [DM.ones((12, 1)) * value] penalty_type = penalty_origin.CUSTOM if isinstance(penalty_type, (Objective.Lagrange, Objective.Mayer)): penalty = ObjectiveOption(penalty_type) else: penalty = ConstraintOption(penalty_type) with pytest.raises(TypeError): penalty.custom_function = custom_no_mult penalty_type.value[0](penalty, ocp, ocp.nlp[0], [], x, [], [], mult=2) with pytest.raises(TypeError): penalty.custom_function = custom_with_mult penalty_type.value[0](penalty, ocp, ocp.nlp[0], [], x, [], []) with pytest.raises(TypeError): keywords = [ "phase", "list_index", "name", "type", "params", "node", "quadratic", "index", "target", "sliced_target", "min_bound", "max_bound", "custom_function", "weight", ] for keyword in keywords: exec(f"""def custom_with_keyword(ocp, nlp, t, x, u, p, {keyword}): my_values = DM.zeros((12, 1)) + x[index] return my_values""") exec("""penalty.custom_function = custom_with_keyword""") exec( f"""penalty_type.value[0](penalty, ocp, ocp.nlp[0], [], x, [], [], {keyword}=0)""" )
def test_penalty_custom(penalty_origin, value): def custom(ocp, nlp, t, x, u, p, mult): my_values = DM.zeros((12, 1)) + x[0] * mult return my_values ocp = prepare_test_ocp() x = [DM.ones((12, 1)) * value] penalty_type = penalty_origin.CUSTOM if isinstance(penalty_type, (Objective.Lagrange, Objective.Mayer)): penalty = ObjectiveOption(penalty_type, index=0) else: penalty = ConstraintOption(penalty_type, index=0) penalty.custom_function = custom mult = 2 penalty_type.value[0](penalty, ocp, ocp.nlp[0], [], x, [], [], mult=mult) if isinstance(penalty_type, (Objective.Lagrange, Objective.Mayer)): res = ocp.nlp[0].J[0][0]["val"] else: res = ocp.nlp[0].g[0][0] np.testing.assert_almost_equal(res, np.array([[value * mult]] * 12)) if isinstance(penalty_type, Constraint): np.testing.assert_almost_equal(ocp.nlp[0].g_bounds[0][0].min, np.array([[0]] * 12)) np.testing.assert_almost_equal(ocp.nlp[0].g_bounds[0][0].max, np.array([[0]] * 12))