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, (ObjectiveFcn.Lagrange, ObjectiveFcn.Mayer)): penalty = Objective(penalty_type) else: penalty = Constraint(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(pn, mult): my_values = DM.zeros((12, 1)) + pn.x[0] * mult return my_values ocp = prepare_test_ocp() t = [0] x = [DM.ones((12, 1)) * value] penalty_type = penalty_origin.CUSTOM if isinstance(penalty_type, (ObjectiveFcn.Lagrange, ObjectiveFcn.Mayer)): penalty = Objective(penalty_type, index=0) else: penalty = Constraint(penalty_type, index=0) penalty.custom_function = custom mult = 2 penalty_type.value[0](penalty, PenaltyNodes(ocp, ocp.nlp[0], t, x, [], []), mult=mult) if isinstance(penalty_type, (ObjectiveFcn.Lagrange, ObjectiveFcn.Mayer)): res = ocp.nlp[0].J[0][0]["val"] else: res = ocp.nlp[0].g[0][0]["val"] np.testing.assert_almost_equal(res, np.array([[value * mult]] * 12)) if isinstance(penalty_type, ConstraintFcn): np.testing.assert_almost_equal(ocp.nlp[0].g[0][0]["bounds"].min, np.array([[0]] * 12)) np.testing.assert_almost_equal(ocp.nlp[0].g[0][0]["bounds"].max, np.array([[0]] * 12))