From c4b45750de459e284e84a399232781eebd08de54 Mon Sep 17 00:00:00 2001 From: Vadym Doroshenko Date: Sun, 5 Feb 2023 19:56:18 +0100 Subject: [PATCH] Add std --- src/bindings/PyDP/mechanisms/mechanism.cpp | 26 +++++++++++++------ tests/algorithms/test_numerical_mechanisms.py | 13 ++++++++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/bindings/PyDP/mechanisms/mechanism.cpp b/src/bindings/PyDP/mechanisms/mechanism.cpp index 73583d17..6bc14989 100644 --- a/src/bindings/PyDP/mechanisms/mechanism.cpp +++ b/src/bindings/PyDP/mechanisms/mechanism.cpp @@ -117,6 +117,13 @@ class GaussianMechanismBinder { return downcast_unique_ptr( builder.Build().value()); }; + + static std::unique_ptr build_from_std(double std) { + dp::GaussianMechanism::Builder builder; + builder.SetStandardDeviation(std); + return downcast_unique_ptr( + builder.Build().value()); + }; static void DeclareIn(py::module& m) { py::class_ gaus_mech( @@ -127,17 +134,20 @@ class GaussianMechanismBinder { return build(epsilon, delta, l2_sensitivity); }), py::arg("epsilon"), py::arg("delta"), py::arg("sensitivity") = 1.0) + .def_static("create_from_standard_deviation", [](double std) { + return build_from_std(std); + }, + py::arg("std"), + R"pbdoc( + Creates Gaussian mechanism from the given standard deviation. + )pbdoc") .def_property_readonly("delta", &dp::GaussianMechanism::GetDelta, "The 𝛿 of the Gaussian mechanism.") - .def_property_readonly( - "std", - [](const dp::GaussianMechanism& self) { - return dp::GaussianMechanism::CalculateStddev( - self.GetEpsilon(), self.GetDelta(), self.GetL2Sensitivity()); - }, + .def_property_readonly( + "std", [](dp::GaussianMechanism& mechanism) { return mechanism.CalculateStddev(); }, R"pbdoc( - The standard deviation parameter of the - Gaussian mechanism underlying distribution. + The standard deviation of the Gaussian mechanism underlying + distribution. )pbdoc") .def_property_readonly("l2_sensitivity", &dp::GaussianMechanism::GetL2Sensitivity, diff --git a/tests/algorithms/test_numerical_mechanisms.py b/tests/algorithms/test_numerical_mechanisms.py index 137a8aa4..2f6d0103 100644 --- a/tests/algorithms/test_numerical_mechanisms.py +++ b/tests/algorithms/test_numerical_mechanisms.py @@ -82,3 +82,16 @@ def test_gaussian_mechanism(): assert_almost_eq(lower_bound, interval.lower_bound) assert_almost_eq(upper_bound, interval.upper_bound) assert conf_level == interval.confidence_level + + +def test_gaussian_mechanism_create_from_std(): + std = 2.0 + gaussian = num_mech.GaussianMechanism.create_from_standard_deviation(std) + assert gaussian.std == 2 + value = gaussian.add_noise(100) + assert 80 <= value <= 120 # in 10*sigma + assert type(value) is int + value = gaussian.add_noise(200.0) + assert type(value) is float + assert 180 <= value <= 220 # in 10*sigma +