Skip to content

Commit

Permalink
Add std (#443)
Browse files Browse the repository at this point in the history
  • Loading branch information
dvadym authored Feb 6, 2023
1 parent 5b74964 commit 48e6260
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
26 changes: 18 additions & 8 deletions src/bindings/PyDP/mechanisms/mechanism.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ class GaussianMechanismBinder {
return downcast_unique_ptr<dp::GaussianMechanism, dp::NumericalMechanism>(
builder.Build().value());
};

static std::unique_ptr<dp::GaussianMechanism> build_from_std(double std) {
dp::GaussianMechanism::Builder builder;
builder.SetStandardDeviation(std);
return downcast_unique_ptr<dp::GaussianMechanism, dp::NumericalMechanism>(
builder.Build().value());
};

static void DeclareIn(py::module& m) {
py::class_<dp::GaussianMechanism, dp::NumericalMechanism> gaus_mech(
Expand All @@ -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,
Expand Down
13 changes: 13 additions & 0 deletions tests/algorithms/test_numerical_mechanisms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 48e6260

Please sign in to comment.