Skip to content

Commit 48e6260

Browse files
authored
Add std (#443)
1 parent 5b74964 commit 48e6260

2 files changed

Lines changed: 31 additions & 8 deletions

File tree

src/bindings/PyDP/mechanisms/mechanism.cpp

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,13 @@ class GaussianMechanismBinder {
117117
return downcast_unique_ptr<dp::GaussianMechanism, dp::NumericalMechanism>(
118118
builder.Build().value());
119119
};
120+
121+
static std::unique_ptr<dp::GaussianMechanism> build_from_std(double std) {
122+
dp::GaussianMechanism::Builder builder;
123+
builder.SetStandardDeviation(std);
124+
return downcast_unique_ptr<dp::GaussianMechanism, dp::NumericalMechanism>(
125+
builder.Build().value());
126+
};
120127

121128
static void DeclareIn(py::module& m) {
122129
py::class_<dp::GaussianMechanism, dp::NumericalMechanism> gaus_mech(
@@ -127,17 +134,20 @@ class GaussianMechanismBinder {
127134
return build(epsilon, delta, l2_sensitivity);
128135
}),
129136
py::arg("epsilon"), py::arg("delta"), py::arg("sensitivity") = 1.0)
137+
.def_static("create_from_standard_deviation", [](double std) {
138+
return build_from_std(std);
139+
},
140+
py::arg("std"),
141+
R"pbdoc(
142+
Creates Gaussian mechanism from the given standard deviation.
143+
)pbdoc")
130144
.def_property_readonly("delta", &dp::GaussianMechanism::GetDelta,
131145
"The 𝛿 of the Gaussian mechanism.")
132-
.def_property_readonly(
133-
"std",
134-
[](const dp::GaussianMechanism& self) {
135-
return dp::GaussianMechanism::CalculateStddev(
136-
self.GetEpsilon(), self.GetDelta(), self.GetL2Sensitivity());
137-
},
146+
.def_property_readonly(
147+
"std", [](dp::GaussianMechanism& mechanism) { return mechanism.CalculateStddev(); },
138148
R"pbdoc(
139-
The standard deviation parameter of the
140-
Gaussian mechanism underlying distribution.
149+
The standard deviation of the Gaussian mechanism underlying
150+
distribution.
141151
)pbdoc")
142152
.def_property_readonly("l2_sensitivity",
143153
&dp::GaussianMechanism::GetL2Sensitivity,

tests/algorithms/test_numerical_mechanisms.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,16 @@ def test_gaussian_mechanism():
8282
assert_almost_eq(lower_bound, interval.lower_bound)
8383
assert_almost_eq(upper_bound, interval.upper_bound)
8484
assert conf_level == interval.confidence_level
85+
86+
87+
def test_gaussian_mechanism_create_from_std():
88+
std = 2.0
89+
gaussian = num_mech.GaussianMechanism.create_from_standard_deviation(std)
90+
assert gaussian.std == 2
91+
value = gaussian.add_noise(100)
92+
assert 80 <= value <= 120 # in 10*sigma
93+
assert type(value) is int
94+
value = gaussian.add_noise(200.0)
95+
assert type(value) is float
96+
assert 180 <= value <= 220 # in 10*sigma
97+

0 commit comments

Comments
 (0)